首先
搭建vue环境,安装vuex。
入口
新建文件store.js,注册vuex
import Vue from 'vue'
import Vuex from 'vuex'
import User from './storage/user'
Vue.use(Vuex);
export default new Vuex.Store(User)
user.js文件就是存放的数据和操作方法。如下:
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount("#app");
讲一下具体用法:
State
** 用一个对象包裹数据(你需要存放的数据)。user.js 为例,如下
state: {
user_name: 'zhouyicc',
age: 0,
todolist: [
{
id: '0001',
data: '测试一把',
down: true
},
{
id: '0002',
data: '测试二把',
down: false
}
]
},
如果你想在.vue文件中拿到这些数据,(比如我要拿到user_name和age变量)如下:
import {mapState} from 'vuex'
先引入mapState,然后在计算属性computed中使用。
computed: {
...mapState({
username: state => state.user_name,
age: state => state.age
})
},
这样在页面中直接使用<p>{{username}},{{age}}</p>
Getter
从 state 中派生出一些状态。 举个例子:比如我要拿到上面state中的==todolist==数组中down为true的数据。
getters: {
downUser: state => {
return state.todolist.filter(item => item.down)
}
}
想要拿数据和展示如state一样,引入==mapGetters==。
computed: {
...mapGetters({
downuser:'downUser'
})
},
<p>{{downuser.data}}</p>
Mutation和Action
用action去触发mutation,mutation去修改属性。 比如:我要修改上面state中的age属性,我点一次变更一下。
mutations: {
changeAge(state, data) {
state.age = data
}
},
actions: {
changeAge({commit}, data) {
commit('changeAge', data)
}
}
然后在页面中引入==mapActions==,去methods中注册使用,这样就可以直接用this.changeAge调用actions中的changeAge方法。当然你也可以直接用==mapMutations==去调用changeAge,但是官方推荐我们使用actions去触发。官方地址
methods: {
getAge() {
this.changeAge(parseInt(Math.random() * 100))
},
...mapActions({
changeAge:'changeAge'
})
}
getAge就是按钮触发的方法。每次随机数取整
Module
简单而言就是模块切割,一般用于大型复杂数据交互。 比如说我想在刚才的基础上新建一个product.js文件,和user.js结构一样,那么在store.js文件中你需要这么引入。
import Product from './storage/product'
import User from './storage/user'
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
user:User,
product:Product
}
})
在user.js和product.js的属性中添加namespaced: true,使其成为带命名空间的模块,它的所有 getter、action 及 mutation 都会自动根据模块注册的路径调整命名,我理解的是不会造成命名冲突问题。
还是以user.js为例,使用如下:
...mapState({
username: state => state.user.user_name,
age: state => state.user.age
})
上面的user就是刚才modules中的自定义的user属性。
mapActions和mapGetters的使用如下:
...mapGetters({
downuser:'user/downUser'
})
...mapActions({
changeAge:'user/changeAge'
})
用法就是属性值的前面加上user。
其它详见vuex官网