1.首先在获取数据页面,通过this.$store.dispatch触发actions里的方法。
methods:{
update(){
this.$store.dispatch('save',this.num)
}
},
2,在store文件夹下的index.js中的action中使用commit触发mutation中的方法。其中context包含了commit、dispatch等属性。
actions: {
save(context,value){
context.commit('savePath',value)
}
},
3接着,在mutation方法中直接改变state中的数据。
mutations: {
savePath(state,value){
this.state.num = value;
},
},
以上方法针对于参数未确定的情况进行存储,比如在请求后台数据时可以这个写。
若想要存储的数据已经确定,可直接在页面中使用this.$store.commit触发mutation里的方法,直接对store中的数据进行修改。
数据的拿取
在页面中,可以通过this.$store.state.属性名
来访问
组件访问 State 数据的第二种方式
基于 Vuex 提供的 mapState 辅助函数,可以方便的把 Store 中指定的数据,映射为当前组件的计算属性
<script>
// 1.按需导入辅助函数mapState
import { mapState }from 'vuex'
export default {
data(){
return{
}
},
computed: {
// 2.把需要的全局数据,映射为当前组件的计算属性。
...mapState(['xxx']),
...mapState({'新名字': 'xxx'})
}
}
</script>