vuex是一个专为vue.js应用程序开发的状态管理模式,他采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
简而言之就是大家都要用的数据,大家都不要拿,放在vuex中
安装
npm i vuex --save
安装vuex报错
如果直接安装vuex,不指定版本的话,就会直接安装最新的vuex的版本
解决办法
1.检查一下适应的Vuex版本号
npm view vuex versions --json
2.安装特定的版本,如版本3.6.2
npm i vuex@3.6.2 --save
基本使用
Base
main.js
// 1.引入
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
new Vue({
render: h => h(App),
// 2.实例化仓库对象
store: new Vuex.Store({
// state 数据
state: {
name: '妲己',
age: 18
},
// mutations 用来修改state的方法,只能做同步操作
mutations: {
// mutations中的第一个参数是该仓库的状态集合(state)
changeWang(a) {
a.name = '王昭君'
},
// mutations中的第二个参数是传入的参数
changeName(state, name) {
state.name = name
}
}
})
}).$mount('#app')
组件中
export default {
// 先打印看看仓库
mounted() {
console.log(this.$store);
}
};
模板中
<!-- A组件 -->
<template>
<div class="container">
<h3>This is A 组件</h3>
<h5>姓名: {{ $store.state.name }}</h5>
<!-- 通过 仓库.commit('方法名', '参数') 修改数据 -->
<button @click="$store.commit('changeWang')">王昭君</button>
<button @click="$store.commit('changeName', '貂蝉')">貂蝉</button>
</div>
</template>
<!-- B组件 -->
<template>
<div class="container">
<h3>This is B 组件</h3>
<h5>姓名: {{ $store.state.name }}</h5>
<h5>年龄: {{ $store.state.age }}</h5>
</div>
</template>
Case
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = new Vuex.Store({
state: {
name: '妲己',
age: 18,
arr: []
},
mutations: {
changeWang(a) {
a.name = '王昭君'
},
changeName(state, name) {
state.name = name
},
changeArr(state, arr) {
state.arr = arr
}
},
// actions 触发事件的时候,所有的逻辑,做完逻辑,提交到mutations修改state
// 处理异步操作(同步也可以)--actions中的第一个参数是该仓库自己
actions: {
reqArr(context) { //context上下文
//通过计时器来模拟异步
setTimeout( () => {
// actions只做逻辑,只有mutations才能修改state的数据
context.commit('changeArr', ['嘿嘿', '嘻嘻'])
}, 3000)
}
}
})
export default store
mian.js引入挂载
import store from './store'
new Vue({
render: h => h(App),
store
}).$mount('#app')
注意:在 state
和 mutations
中分别补充相应的数据和方法(这里我就不展示啦噜)
组件
export default {
mounted() {
console.log(this.$store.dispatch);
// 通过dispatch触发actions
this.$store.dispatch('reqArr')
}
};
actions推荐写法
注意Vuex的介绍–以相应的规则保证状态以一种可预测的方式发生变化(避免跳过actions直接修改数据)
actions: {
changeAge(context, age) {
context.commit('changeAge', age)
}
}
模板
<button @click="$store.dispatch('changeAge', 26)">通过actions更改年龄</button>
总结—vuex是单向数据流
state --> components -->dispatch --> actions --> commit --> mutations --> 修改(mutate) --> state --> components …
💡
state
决定了components
展示的样子,然后在组件中可以通过dispatch
触发actions
做逻辑,然后actions
会commit
到mutationas
,mutations
开始修改(mutate),修改完成后state
发生变化,从而components
再次发生改变