要用一个框架,要先看这个框架是用来解决什么问题的。
Vuex目前为止我觉得作用主要有两个:
- 解决数据流的问题:子组件只能通过props接收参数,但不能直接修改参数值,在没有vuex的情况下,只能通过冒泡解决,而vuex解决了这一问题。
- 实现了关键数据的集中管理
vuex核心总共有四个部分:
- state,这是数据的存储部分,下面是一个简单的例子(为了方便,都是直接引用cdn在html页面上测试,没有使用node)
//html部分
<div id="example_6_1">
<div2 ></div2>
</div>
<div id ="example_6_2">
<button2></button2>
</div>
//script部分
Vue.component('div2',{
template:`<div>{{count}}</div>`,
computed: {
count(){
return this.$store.state.count;
}
},
})
Vue.component('button2',{
template:`<button v-on:click="click_event">{{count}} add 1</button>`,
computed:{
count(){
return this.$store.state.count;
}
},
methods:{
click_event:function(){
console.log("the button is clicked once")
}
}
})
var store = new Vuex.Store({
state:{
count:0
},
mutations:{
increment(state){
state.count++;
}
}
})
new Vue({
el:"#example_6_1",
store:store
})
new Vue({
el:"#example_6_2",
store:store
})
例子实现的是简单的两个组件都以vuex.store对象进行实例化,并将store.state.count属性进行显示,唯一需要注意的地方是,组件在读取自己内部绑定的store对象时,必须写为this.$store.state.XXXX,这是为了区分组件定义成员和用户定义的成员的。
- mutations,这里感觉是用了js动态的特性,简单来说就是子组件通过this.$store.commit('function_name')的方式实现对vuex中state的操作
这里将上述的例子在稍微改动
Vue.component('button2',{
template:`<button v-on:click="click_event">{{count}} add 1</button>`,
computed:{
count(){
return this.$store.state.count;
}
},
methods:{
click_event:function(){
console.log("the button is clicked once")
this.$store.commit("increment");
}
}
})
这样就实现了按钮按下时两个组件显示数值同时+1的操作
网友评论