适用场景
- 全局共享数据,抛开繁琐的组件传值;
- 什么数据适合全局共享?(组件的共享数据);
- 好处?(谁要用,直接获取,组件修改其他的也变化);
- 数据管理集中化,全局管理方便;
如何在项目中使用vuex
- 下载
cnpm i vuex -S
- 导入,挂载vuex(main.js中)
import Vuex from 'vuex'
Vue.use(Vuex)
- 创建store对象
const store = new Vuex.Store({
state: {
number:5,
}
})
- 将store挂载到vm上
new Vue({
el: '#app',
router,
render: h => h(App),
store
})
this.$store.state.数据名称的调用
.vue组件调用:(第一种直接使用)
<template>
<div>
{{this.$store.state.number}}
</div>
</template>
.vue组件调用:(第二种导入辅助函数)
import {mapState} from 'vuex'
computed:{
...mapState(['number'])
}
页面直接使用
<div>{{number}}</div>
mutations:如果要修改state的数据需要在store中调用方法
全局定义使用:
const store = new Vuex.Store({
state: {
chuanc:10,
},
mutations: {
add(state){
state.chuanc += 2
},
}
})
调用辅助函数mapMutations
import {mapState,mapMutations } from 'vuex'
调用方法:
methods: {
...mapMutations(['add'])
},
computed:{
...mapState(['chuanc'])
}
组件展示:
<div>
{{chuanc}}
<button @click="add">添加</button>
</div>
getters的使用(相当于计算属性):
- getters中定义的方法,就相当于vue的计算属性;
- getters变化了那么getters生成的数据也会变化;
![在这里插入图片描述](https://img-blog.csdnimg.cn/2020050809485740.jpg?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NjM5OTI1OA==,size_16,color_FFFFFF,t_70#pic_center)