Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。
1.vuex的5种状态
{
//state 存放数据,使用时通过 $store.state.counter 即可拿到数据,类似Vue中的data。
state: {},
//getters 处理state中的数据并返回新数据,具有缓存功能,类似计算属性computed
getters: {},
//mutations 突变,修改state的唯一方式,只能做同步操作,定义的方法名不能重复
mutations: {},
//actions 动作,处理异步操作,获取后台响应,提交数据给突变mutations
actions: {},
// 状态机可以有多个,modules用来存放各模块的状态机
modules: {}
}
2.在vue-cli脚手架中使用
注意:vuex4版本以上只能在vue3中使用,vue2使用vuex3版本,安装时如果不指定版本,会安装最新版本的vuex
如果打印$store找不到,有可能版本不匹配 vue2使用vuex3 ,vue3 使用vuex4。
1.安装
npm install vuex@3 -S
2. store.js
import Vue from "vue";
import Vuex from 'vuex';
Vue.use(Vuex)
export default new Vuex.Store({
state:{
l_name:'测试四',
l_count:4
},
getters:{
fullNmae(state){
return state.l_name+'111';
}
},
mutations:{
updateName(state,obj){
console.log(obj);
state.l_name = obj.lname;
}
},
actions:{
actionUpdateName(context,obj){
console.log(obj);
context.commit('updateName',obj)
}
},
})
3.注入仓库
Vuex 通过 store 选项,提供了一种机制将状态从根组件“注入”到每一个子组件中(需调用 Vue.use(Vuex)):main.js
import Vue from 'vue'
import App from './App'
//当前处于开发阶段,无需显示生产模式提示的信息。
Vue.config.productionTip = false;
import VueRouter from 'vue-router';
Vue.use(VueRouter);
import routes from './router/index';
import store from './store/store';
new Vue({
el: '#app',
router,
store,
render: h => h(App)
})
4.访问仓库数据
root根store取值
this.$store.state.counter
this.$store.getters.fullNmae
this.$store.commit('updateName',{'lname':'用户无'})
this.$store.dispatch('actionUpdateName',{'lname':'用户无'})
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';
...mapState(['l_name']),
...mapGetters(['fullNmae']),
<template>
<div id="home">
<p @click="upname">更换名字</p>
<p>{{l_name}}</p>
<p>{{fullNmae}}</p>
</div>
</template>
<script>
import { mapState, mapGetters, mapActions, mapMutations } from 'vuex';
export default {
data () {
return {
}
},
computed:{
// 基础写法:
l_name(){
return this.$store.state.l_name
},
// 简化写法
...mapState(['l_name']),
// 基础写法:
fullname(){
return this.$store.getters.fullNmae
},
// 简化写法
...mapGetters(['fullNmae']),
},
methods:{
...mapMutations({
upname(commit){
commit('updateName',{'lname':'用户无'})
}
}),
...mapActions({
upname(dispatch){
dispatch('actionUpdateName',{'lname':'用户无'})
}
})
}
</script>
<style>
</style>