引入vuex
1.利用npm包管理工具,进行安装 vuex。在控制命令行中输入下边的命令就可以了。
npm install vuex --save
2.新建一个vuex文件夹(这个不是必须的),并在文件夹下新建store.js文件,文件中引入我们的vue和vuex。
然后写store.js
import Vue from 'vue'
import Vuex from 'vuex'
//安装vuex
Vue.use(Vuex)
//声明状态常量对象
const state = {
count: 1
}
//需要改变state的值,必须通过mutations,意思为改变
//在mutations里声明方法
const mutations = {
add(state){
state.count++;
},
reduce(state){
state.count--;
}
}
//导出
export default new Vuex.Store({
//导出状态常量
state,
//导出mutations
mutations
})
创建新组件Count.vue
<template>
<div>
<h1>{{ msg }}</h1>
<!--直接引用store里的数据-->
<h2>{{ $store.state.count }}</h2>
<!--提交store里mutations内的方法-->
<button @click="$store.commit('add')">+</button>
<button @click="$store.commit('reduce')">-</button>
</div>
</template>
<script>
import store from '../vuex/store'
export default {
data(){
return {
msg: 'Hello Vuex!'
}
},
//将store添加到实例
store
}
</script>
<style>
</style>
配置路由
import Count from '@/components/count'
export default new Router({
// mode:'history',//是否现显示地址栏hash那个#号
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/count',
name: 'count',
component: Count
}
]
})
另外也可以在main.js中引入store成为全局的
import store from '@/vuex/store'
Vue.use(store)
new Vue({
el: '#app',
store,//将store添加到vue实例
router,
template: '<App/>',
components: { App }
})
提示:引入文件路径中的@表示src路径,是自动在webpack.base.conf.js里面配置的