1. 为什么使用Vuex?
在Vue的组件化开发中,父组件和子组件之间可以相互传递数据,但是依然有两个问题:
- 如果想在子组件中获取祖先组件(父组件以上的组件)中的数据,必须一层一层的进行传递
- 如果两个兄弟组件想传递数据,则必须先将数据传递给父组件,借助父组件才能完成兄弟组件传递数据;如果两个组件不在同一个父组件内,则也需要传递到祖先组件。
通过以上两个问题可以看出,不使用Vuex的情况下,兄弟组件之间传递、共享数据有多麻烦。
使用Vuex,可以将组件中公共的部分抽取出来,独立于各个组件,程序中的任何组件都可以获取和修改Vuex保存的公共数据。
2. 如何使用Vuex?
四个步骤:引入Vuex、创建Vuex对象、保存store、使用Vuex
2.1 引入Vuex
在官网下载Vuex:vuex.vuejs.org/zh/installa…
<script src="https://juejin.cn/post/lib/vue.js"></script>
<!-- 1. 导入Vuex -->
<!-- 注意点:在导入Vuex之前必须先导入Vue -->
<script src="https://juejin.cn/post/lib/vuex-3.6.2.js"></script>
复制代码
2.2 创建Vuex对象
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 如果已经通过script引入了vuex文件可以忽略以上代码
const store = new Vuex.Store({
state: {
count: 0
},
// 注意点:在执行mutations中定义的方法的时候,系统会自动给这些方法传递一个state参数
// state中就保存了共享的数据
mutations: {
increment (state) {
state.count++
}
}
})
复制代码
- state:相对于组件中的data,专门用于保存共享数据
// 在组件中可以通过"this.$store.state.变量名"来获取vuex中的数据,this.$store.state是固定字段
console.log(this.$store.state.count); // 0
复制代码
- mutations: 定义在vuex内部的,用于对vuex保存数据进行操作的函数,在vuex中不推荐由组件直接修改vuex中的数据,通过调用在vuex内部定义的函数更有利于维护代码。
// 在组件中可以通过"this.$store.commit("函数名")"来调用vuex中的函数
add() {
this.$store.commit("increment");
}
复制代码
2.3 添加store的key
在祖先组件(最外层的组件)中添加stroe,在祖先组件中定义的组件就都可以使用vuex
const store = new Vuex.Store({
// 这里的state就相对于组件中的data,就是专门用于保存共享数据的
state: {
msg: "深海鱼"
},
/* mutations: {
increment(state) {
state.count++
}
} */
});
Vue.component("grandfather", {
template: "#grandfather",
// 3. 在祖先组件中添加store的key保存Vuex对象
// 只要祖先组件中保存了Vuex对象,那么祖先组件和所有的后代组件就可以使用Vuex中保存的共享数据
store,
// 父组件
components: {
"father": {
template: "#father",
components: {
"son1": {
template: "#son1",
}
}
}
}
})
复制代码
2.4 使用Vuex
可以直接使用规定的字段来获取Vuex中的数据
<template id="grandfather">
<div>
<h1>{{this.$store.state.msg}}</h1>
<father></father>
</div>
</template>
<!-- 父组件使用vuex -->
<template id="father">
<div>
<!-- 4. 在使用Vuex中保存的共享数据的时候,必须通过如下的格式来使用 -->
<h2>{{this.$store.state.msg}}</h2>
<son1></son1>
</div>
</template>
<!-- 子组件使用vuex -->
<template id="son1">
<div>
<h3>{{this.$store.state.msg}}</h3>
</div>
</template>
复制代码
3. getters属性
Vuex的getters相对于组件中的计算属性
const store = new Vuex.Store({
// state:用于保存共享数据
state: {
msg: "深海鱼"
},
// mutations: 用于保存修改共享数据的方法
mutations: {
},
getters: {
format(state) {
console.log("getters方法被执行了");
return state.msg + '没了没了';
}
}
});
复制代码
<template id="father">
<div>
{{this.$store.state.msg}}
{{this.$store.getters.format}}
{{this.$store.getters.format}}
{{this.$store.getters.format}}
</div>
</template>
复制代码
输出结果:
暂时写到这里,Vuex之后的部分会随着学习不断更新。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END