Vuex状态管理模式
vuex是什么?
是实现组件全局状态(数据)管理的一种机制,可以方便的实现组件之间数据的共享
好处:
①能够在vuex中,集中管理共享的数据,易于开发和后期维护
②能够高效地实现组件之间的数据共享,提高开发效率
③存放在vuex中的数据都是响应式的,能够实时保持数据与页面的同步
安装: npm install vuex --save
使用:src里面创建store文件夹
创建index.js配置vuex 如图:


在index.js文件中引入:
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
export default new Vuex.Store({
state: {
//存放的内容所有组件都可以访问,类似于data
name:"张三'
},
mutations: {},
actions: {},
modules: {},
});
在main.js:
import store from "./store";
Vue.config.productionTip = false;
new Vue({
router,
store,
render: (h) => h(App),
}).$mount("#app");
其他组件中使用:
<template>
<div class="about">
<h1>This is an about page</h1>
{{name}}
</div>
</template>
<script>
export default {
computed:{
name(){
return this.$store.state.name
}
}
}
</script>
他有5个核心属性:State,Getter,Mutation,Action,Module
state
提供唯一的公共数据源,所有共享数据都要统一放到Store的State中进行存储
创建store数据源,
const store = new Vuex.Store({
state:{
name:"张三"
}
})
组件访问State中的数据
第一种
this.$store.state.全局数据名称
this.$store.state.name
第二种
//1.从vuex 中按需导入mapState 函数
import {mapState} from "vuex"
//2.通过刚才导入的mapState函数,将当前组件需要的全局数据,映射为当前组件的computed计算属性
computed:{
...mapState(['name'])
}
单一状态树,state里面的状态
使用计算属性获取最简单
computed:{
name(){
return this.$store.state.name
}
注意:在其他方法中不要直接修改state里面的属性,想要修改请使用Mutation
下一篇文章会详细的解说他的mutaion,action,感谢观看

Vuex是一个用于实现组件全局状态管理的机制,便于集中管理共享数据和提高开发效率。通过安装和配置Vuex,创建State来提供唯一的公共数据源,组件可以通过计算属性或getter访问。注意不应直接修改State,而应使用Mutation进行更新。
898

被折叠的 条评论
为什么被折叠?



