<!--
一、什么时候使用Vuex
如果应用比较简单,就不需要使用Vuex,直接使用父子组件传值及及它传值方式即可,使用Vuex就要额外的引入vuex的框架,可能是繁琐冗余的
如果需要构建一个中大型单页应用,就可以使用vuex更好地在组件外部管理状态
二、 Vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。
它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
三、Vuex的五个核心概念
1. state: 存储公共数据
2. mutations: 不能包含异步操作
更改 Vuex 的 store 中的状态的唯一方法是提交 mutation
mutation的方法中有两个参数,第一个是state,第二个是参数
mutations: {
方法名(state,参数){
state.属性 = 参数
}
}
在组件中提交mutations的方法: this.$store.commit("方法名",参数)
***** state中的数据是响应式的,数据改变,相关视图会重新渲染
3. actions:
Action 类似于 mutation,不同在于:
Action 提交的是 mutation,而不是直接变更状态。(action不能直接更改state数据)
Action 可以包含任意异步操作。
*****总结一下:
mutation不能有异步操作,而action可以有异步操作
mutation可以直接更改数据,而action只能通过提交mutation,通过mutation的方法来改变数据
实际通过组件改变数据时,如果没有异步操作,可以直接提交mutation,如果有异步操作,必须派发action,通过action提交mutation来更改数据
4. getters: 就像计算属性一样,getter 的返回值会根据它的依赖被缓存起来,且只有当它的依赖值发生了改变才会被重新计算
-->
<div id="app">
<com-a></com-a>
<hr>
<com-b></com-b>
</div>
<script src="./js/vue.js"></script>
<script src="./js/vuex.js"></script>
<script>
//定义状态管理仓库: store
const store = new Vuex.Store({
state: {
msg: '公有的数据',
score: [35,78,90,98,89,100],
goodsList: []
},
actions:{
//第一个参数是context,第二个是数据(payload载荷)
getGoodsList(ctx, type){
console.log(ctx,type);
//用定时器模拟异步请求
setTimeout(()=>{
let data = [
{
"id": 1,
"goodsName": "红米"
},
{
"id": 3,
"goodsName": "小米"
}
]
//通过提交mutation来改变数据
ctx.commit("getGoodsList",data)
},5000)
}
},
mutations: {
changeMsg(state,newMsg){
// console.log('state',state);
// console.log('newMsg',newMsg);
state.msg = newMsg
},
getGoodsList(state,data){
state.goodsList = data
}
},
// 类似computed
getters: {
goodScore(state){
return state.score.filter(item=>item>=90)
}
}
})
// 定义两个组件
// A组件实现的需求:
// 1. 读取store中的公共数据
// 2. 单击按钮时,通过提交mutation来更改store中的数据
// 3. 在组件初始化时,通过ajax请求获取公共数据
// 4. 遍历显示所有成绩>90的分数
const ComA = {
template: `
<div class="box box1">
组件A的内容
<hr>
<button @click="send">通过A组件修改公有数据</button>----{{$store.state.msg}}
<ul v-if="$store.getters.goodScore.length">
<li v-for="(item,index) in $store.getters.goodScore">{{item}}</li>
</ul>
</div>
`,
methods: {
send() {
//直接修改state数据是不被推荐的
// this.$store.state.msg = '改变过的'
// 通过commit()提交mutations,来改变state的数据
this.$store.commit("changeMsg",'改变过的msg')
}
},
created(){
//通过dispatch派发action,action中有异步请求
this.$store.dispatch("getGoodsList",'book')
},
// computed: {
// goodScore(){
// return this.$store.state.score.filter(item=>item>=90)
// }
// }
}
const ComB = {
template: `
<div class="box box2">
组件B的内容---{{$store.state.msg}}
<ul v-if="$store.state.goodsList.length">
<li v-for="(item,index) in $store.state.goodsList">{{item.goodsName}}</li>
</ul>
</div>
`
}
var vm = new Vue({
el: '#app',
data: {
},
// 注册store
store: store,
methods: {},
components: { ComA, ComB }
});
</script>