vuex是在一个应用中只有一个store对象,用来存储数据state,以及修改数据的方法,用于组件间的传值
<div id="app">
<!-- 子组件给父组件传值 -->
<div>father{{this.$store.state.count}}</div>
<!-- 父组件给子组件传值 -->
<son></son>
</div>
<script>
Vue.component("son",{
template:`<div><div>son {{qq}}</div><button @click="cpt">computed</button></div>`,
computed:{
qq(){
return this.$store.getters.GetList(11)
}
},
methods:{
cpt(){
this.$store.commit({
type: 'setc',
zhi: 10
})
}
}
})
var store = new Vuex.Store({
//存储数据变量的
state: {
count: 0,
datalist:[]
},
//直接修改state中变量的值,只能通过这种方法
mutations: {
increment(state) {
state.count++
},
setc(state,payload){
state.count+=payload.zhi
}
},
//这个是将state中的值取出来再次处理后返回(注意这个不能改变state中变量的值),这个是类似computed,值会被缓存,当依赖项(比如参数)发生改变时才会从新计算
getters:{
add:state=> n=>{
return state.datalist=n
},
pp:state=> n=>{
return state.count+n
},
GetList:state=>cc=>{
return state.count+cc
}
}
})
new Vue({
el: '#app',
store,
computed:Vuex.mapGetters(['add','pp'])
})
</script>