1.介绍
VueX它采用集中式存储管理应用的所有组件的状态
可以理解为:
一个数据,或者方法可以在多页组件中加以引用运用。可以理解为一个前端数据库。也可以理解为在全Vue中设置一个变量,每个组件都可以加以引用并使用。
2.配置store
1.代码
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//数据是储存在这里
state:{
},
//改变state中的数据要用mutations 他相当于页面组件中的同步方法
mutations:{
},
/* 他相当于页面组件中的计算属性 */
getters:{
},
/* 他相当于页面组件中的异步方法 */
actions:{
},
/* 模块化 */
modules:{
}
})
2.1.export default new Vuex.Store
用Vuex中的Store方法,构造一个实例对象。然后透过export default发送出去
2.2.state
数据存储在这里
2.3.mutations
改变state中的数据要用 mutations ,这个相当于页面组件中的同步方法
2.4.getters
他相当于页面组件中的计算属性
2.5.actions
他相当于页面组件中的异步方法
2.6.modules
模块化
3.Store中的使用
3.1 state和getter
state作为数据存储的地方,getter则是相当于计算属性。在getter中想要使用state中的数据,则要把state当作参数传到getter中。
getters: {
//筛选正确的
activeList(state) {
return state.list.filter(v => v.status)
},
/* getters中的第二个参数就是getters本身 */
getList(state,getters){
return getters.activeList.filter(v=>{
return v.id > 5
})
},
},
注:getter相当于计算属性,所以getter需要返回
3.2 mutation和action
mutation是同步操作,而且改变state中的数据只能用 mutations。mutation中的参数有两个,第一个是 state ,第二个是载荷,也可以就是从页面中传递进来的数值。
mutations: {
//mutations种第二个参数是载荷 也就是需要传递进来的数据
addlist(state, preload) {
console.log(preload)
state.students.push(preload)
}
},
action是异步操作,他可以调用mutation 和 getter。mutation中的参数有两个,第一个一定是 context ,第二个是载荷,也可以就是从页面中传递进来的数值。
/* 他相当于页面组件中的异步方法 */
actions: {
/* actions带参数情况 */
test(context){
console.log(context);
setInterval(()=>{
context.commit('add')
},1000)
}
},
context可以使用console.log来打印出来。
其中context可以用解构函数来结构。
/* 他相当于页面组件中的异步方法 */
actions: {
/* actions带参数情况 */
test({commit,state,getters}, res) {
setInterval(() => {
commit('addn', res)
}, 1000)
}
},
可以看出 context中包含state,getter,commit等。其中commit是调用mutation的。
3.3modules
Vuex 允许我们将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割。
而分割的模块我们需要在modules中声明
4.页面中的使用
4.1使用的位置
state和getter在 页面中的计算属性(computed)中使用;而mutation和action则在方法(methods)中使用。
4.2使用的方法
4.2.1 使用辅助函数
<template>
<div class="home"></div>
</template>
<script>
//先使用 improt 从vuex中引用,并解构
import { mapState, mapGetter, mapMutations, mapAction } from "vuex";
export default {
name: "Home",
data() {
return {};
},
computed: {
...mapState({
number: (state) => state.home.num,
}),
...mapGetter({
number: (getter) => getter.test,
}),
//或者
//其中num是state中定义的属性
...mapState(["num"]),
//其中test是getter中定义的方法
...mapGetter(["test"]),
},
methods: {
...mapMutations({
add: "add",
sub: "sub",
}),
//或者
//其中test是mutation中定义的方法
...mapMutations(["text"]),
},
};
</script>
其中参数可以在store中直接使用。
4.2.2通过方法访问
state使用: $store.state.num
getter使用:$store.getter.test
mutation使用: $store.commit('test')
action使用:$store.dispatch('test')
<template>
<div class="home">
</div>
</template>
<script>
export default {
name: "Home",
data() {
return {
};
},
computed: {
test() {
this.$store.state.num;
},
test2() {
this.$store.getter.num;
},
},
methods: {
test() {
this.$store.commit("addlist", this.list);
},
test2() {
this.$store.dispatch("addlist", this.list);
},
},
};
</script>
未完待续···