第一步:
在共享组件中的state准备好测试数据:
const state = {
personList:[
{id:'001',name:'罗小黑'},
]
}
在单独组件A中编写模板,并且从state中读取数据,遍历出来。
<template>
<div>
<ul>
<li v-for="p in personList" :key="p.id">{{p.name}}</li>
</ul>
</div>
</template>
<script>
export default {
name:'Person',
computed:{
personList(){
return this.$store.state.personList
}
}
}
</script>
OR
在单独组件A中引入mapState,使用mapState的对象写法或者数组写法
<script>
import {mapState} from 'vuex'
export default {
name:'Person',
computed:{
...mapState(['personList'])//数组写法
// ...mapState({personList:'personList'})//对象写法
}
}
</script>
第二步:
在单独组件A中双向绑定数据和方法
<template>
<div>
<input type="text" placeholder="请输入名字" v-model="name">
<button @click="add">添加</button>
<ul>
<li v-for="p in personList" :key="p.id">{{p.name}}</li>
</ul>
</div>
</template>
<script>
import {nanoid} from 'nanoid'
export default {
name:'Person',
data(){
return {
name:''
}
},
methods:{
add(){
const personObj = {id:nanoid(),name:this.name};
this.$store.commit('ADD_PERSON',personObj);
this.name='';//清空
}
},
computed:{
personList(){
return this.$store.state.personList
},
}
}
</script>
在共享组件中准备用于操作的数据
const mutations = {
ADD_PERSON(store,value){
console.log('mutations中的ADD_PERSON被调用了',store,value);
state.personList.unshift(value);
}
}
第三步:
- 在单独组件A中读取单独组件B的数据
在单独组件A中的computed中编写单独组件B的数据,接着就可以在A中直接使用B中的数据sum了。
computed:{
sum(){
return this.$store.state.sum
}
- 在单独组件B中读取单独组件A的数据
同样,也是在B中的computed计算属性中编写A中的数据,使得B中的temple模板可以直接使用A中的personList;以此达到用Vuex来共享组件A和组件B中的数据。
computed:{
// 借助mapState生成计算属性,从state中读取数据。(数组写法)
...mapState(['sum','school','subject','personList']),
}