vuex的下载以及使用
- 封装到store文件中的store.js
//首先下载vuex的包 vue2对应vuex3 vue3对应vuex4
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
//这里写配置项
state:{},
mutations:{},
actions:{},
getters:{},
modules:{}
})
export default store
//在main.js入口文件中 引入并挂载到vue实例中
import store from '@/store/index.js';
new Vue({
store,
render: (h) => h(App),
}).$mount("#app");
- 直接引入到main.js中(不建议)
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex)
const store = new Vuex.Store({
//这里写配置项
state:{},
mutations:{},
actions:{},
getters:{},
modules:{}
})
new Vue({
store,
el: '#app'
})
3.state的三种使用方法
//假设state中的数据为:
state: {
count: 0,
age: {
age1: {
age2: 30,
},
},
list: [1, 2, 3, 4, 5, 6],
color:'red'
}
//现在我们需要在各个组件中拿取数据
1.用 $store.state. 来获取数据
//可以获取深层次嵌套的数据
{{$store.state.age.age1.age2}}
//注意 别看他这么长 你把它就当做一个数据 不仅仅可以用在插值表达式中
//也可以这么用 你就把这么一长串看做是一个数据data
<div :style="{ color: $store.state.color }">颜色</div>
2.在计算属性中写一个函数 函数名自定义一个贴切的名字
computed: {
count () {
return this.$store.state.count
},
color () {
return this.$store.state.color
}
}
//这个renturn 后面接的就是用 this.$store 这个方法取得的值
//return 就是将值返回给 count 这个函数
//因为是在计算属性中 count 可以当做是一个变量使用
//所以在html中就可以这么用:
{{count}}
或者:
<div :style="{ color: color }">颜色</div>
3. 引入辅助函数
//这里是用到解构 vuex 里面 有mapState这个对象 用{mapState}直接拿到
import {mapState} from 'vuex'
//在 计算属性computed 中运用该方法 因为state有许多数据 所以要用[]放数据变量
//但是这个没有办法获得深层次数据
...mapState(['count','age','list','color'])