vuex
是数据统一集中管理的解决档案,避免了vue
组件之间传递数据的麻烦,且其state
值同样使用双向数据绑定。
下面利用webpack搭建平台。
1. 在根组件中声明
import Vue from 'vue'
import VueX from 'vuex'
import index from './index.vue'
Vue.use(VueX);
const store = new VueX.Store({
state: {
count: 1,
todos: [
{id: 1, text: '...', done: true},
{id: 2, text: '...', done: false}
]
}
});
var root = document.createElement('div');
new Vue({
store,
render: (h) => h(index)
}).$mount(root);
2. 子组件中使用state
this.$store.state.count;
在子组件中对store.state
值的改变会同步体现在其他组件中。
3. 数据统一同步管理mutations
const store = new VueX.Store({
state: {
count: 1,
todos: [
{id: 1, text: '...', done: true},
{id: 2, text: '...', done: false}
]
},
mutations: {
increment(state,n) {//这里的state参数不管什么形式都是上面的state。
state.count+=n;
},
decrease(state) {
state.count--;
}
}
});
mutations
中是对state
数据进行统一操作,方便记录数据变化,不允许在子组件中直接操作state
,虽然这样操作可以改变state
值,但不推荐。
同时mutations
中的操作都是同步的。
4. 子组件中使用mutations方法commit
this.$store.commit('increment',5);
this.$store.commit('decrease');
5. 数据统一管理之异步actions
const store = new VueX.Store({
state: {
count: 1,
todos: [
{id: 1, text: '...', done: true},
{id: 2, text: '...', done: false}
]
},
actions:{
incrementAsync({commit},obj){//这里的commit必须用花括号
return new Promise(function (resolve,reject) {
setTimeout(function () {
commit('increment',obj.amount);
resolve(123);
},1000)
})
}
}
});
6. 子组件中使用actions方法dispatch
countAdd() {
this.$store.dispatch('incrementAsync',{
amount:10
}).then(function (data) {
alert(data);
console.log(data);
})
}
7. getter优先处理
const store = new VueX.Store({
state: {
count: 1,
todos: [
{id: 1, text: '...', done: true},
{id: 2, text: '...', done: false}
]
},
getters:{
doneTodos: state => {//这里的形参不管是什么都代表store.state.
return state.todos.filter(todo => {return todo.done});
}
}
});
8. 子组件中使用getters
this.$store.getters.doneTodos;
9. 子组件中使用map简化store中状态的引用。
import { mapState } from 'vuex'
import { mapGetters } from 'vuex'
import { mapActions } from 'vuex'
export default {
computed: {
...mapState({
count:'count'
}),
...mapGetters({
doneTodos:'doneTodos'
})
},
methods: {
...mapActions({
incrementAsync:'incrementAsync'
})
}
}
这里需用配置babel
以解析扩展运算符。
在webpack.config.js
中添加js
解析loader
{
test: /\.js/,
loader: 'babel-loader',
exclude:/node_modules/
},
配置.babelrc
文件
{
"presets": [
["env", {
"es2015": { "modules": false }
}],
"stage-3" // 一定不要忘记
],
"plugins": ["transform-runtime"]
}
安装以下依赖
"babel": "^6.23.0",
"babel-core": "^6.26.0",
"babel-loader": "^7.1.4",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.6.1",
"babel-preset-es2015": "^6.24.1",
"babel-preset-stage-3": "^6.24.1",
此时可在子组件中直接引用。
<p>show count mapState countAlias:{{count}}</p>
<p>show count done todos:{{doneTodos}}</p>
<input type="button" @click="incrementAsync({amount:20})" value="increase aysnc">