为什么用vuex?
组件子间传值有局限,不能处理复杂的情况,
什么情况下使用:
两个组件或更多组件都要用到同样的数据,跨多个组件传值,记录用户登录信息,(不需要多个组件传递用户信息,需要的时候去vuex里面去取就可以了)
新建vuex:
state:相当于data,数据不能随便更改,只能通过mutations(相当于methods)修改
getters:相当于computed,计算属性,依赖改变触发
mutations:相当于methods,每个方法都有两个参数,第一个是state,不需要传,第二个是data
actions:相当于 async methods 存放异步的方法
modules:模块
const store = new Vuex.Store({
state: {
},
getters: {
},
mutations: {
},
actions: {
},
modules: {
}
})
示例:点击组件内的按钮修改vuex里面的值,同时另一个组件使用watch监听 s t o r e . s t a t e . m s g 同 步 修 改 , 或 者 另 一 个 组 件 直 接 在 模 板 内 显 示 store.state.msg同步修改,或者另一个组件直接在模板内显示 store.state.msg同步修改,或者另一个组件直接在模板内显示store.state.msg
<div id="app">
<aaa></aaa>
<hr>
<bbb></bbb>
</div>
<script>
const store = new Vuex.Store({
state: { //相当于data
msg: 20,
},
//相当于methods 方法 state里面的值不允许直接修改,需要在mutations里面修改
mutations: {
setAdd(state, data) {
state.msg = data
}
},
})
Vue.component('aaa', {
template: `<div>
<h1>{{zj}}</h1>
<button @click="add">增加</button>
</div>`,
methods: {
add() {
this.zj += 2
this.$store.commit('setAdd', this.zj)
}
},
data() {
return {
zj: this.$store.state.msg
}
},
})
Vue.component('bbb', {
template: `<h1>{{zj}}</h1>`,
data() {
return {
zj: this.$store.state.msg
}
},
watch: {
'$store.state.msg'(newValye, oldValue) {
this.zj = this.$store.state.msg
console.log(111);
}
},
})
new Vue({
el: '#app',
store,
})
</script>