什么是vuex

Vue
116
0
0
2024-04-15

1.vuex是什么

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式, 采用集中式存储管理应用的所有组件的状态,解决多组件数据通信。

要点:

vue官方搭配,专属使用 (类似于:vue-router),有专门的调试工具 集中式管理数据状态方案 (操作更简洁)data() { return { 数据, 状态 }} 数据变化是可预测的 (响应式)

使用Vuex的好处:

1、数据的存取一步到位,不需要层层传递

2、数据的流动非常清晰

3、存储在Vuex中的数据都是响应式的

那么我们先来思考一个问题:什么样的数据适合存储到Vuex中?

答案是:需要共享的数据

Vuex的作用就是:频繁、大范围的数据共享

vue官方提供的独立于组件体系之外的,管理公共数据的工具

在这里插入图片描述

2.vuex的5个基本概念

1.state:提供唯一的公共数据源,所有共享的数据统一放到store的state进行储存(类似于data(){return {a:1, b:2,xxxxxx}})

在vuex中state中定义数据,可以在任何组件中进行调用

在这里插入图片描述

调用: 方法一:在方法在直接使用:

<p>{{$store.state.userInfo}}</p>
<p>{{$store.state.routers}}</p>

方法二:

this.$store.state.全局数据名称

方法三:

从vuex中按需导入mapstate函数

import { mapState } from "vuex";
computed:{
  ...mapState(["name","age","sex"]),
}
<p>{{$store.state.name}}</p>
<p>{{$store.state.age}}</p>

2.mutations :更改 Vuex 的 store 中的状态的唯一方法是提交 mutation (类似于methods) 在vuex中定义:

state:{
   name:"张三",
   age:12,
   count:2
},
getters:{},
mutations:{
  addcount(state,num){
   state.count=+state.count+num
  },
  reduce(state){
    state.count--;
  }
}

在组件中使用:

<button @click="btn">按钮1</button>

方法一:使用commit触发Mutation操作

methods:{
  //加法
  btn(){
    this.$store.commit("addcount",10)     //每次加十
  }
  //减法
  btn1(){
    this.$store.commit("reduce") 
  }
}

方法二:使用辅助函数进行操作,具体方法同上。

methods:{
 ...mapMutations(["addcount","reduce"]),
 btn(){
 this.addcount(12);
 }
}

3.actions: 发起异步操作,Action和Mutation相似,Mutation 不能进行异步操作,若要进行异步操作,就得使用Action 在vuex中定义:

//异步操作mutation
actions:{
  asyncAdd(context){
    //异步
    setTimeout(() =>{
      context.commit("reduce")
     },1000)
  }
}

在组件中使用: 方法一:直接使用dispatch触发action函数

this.$store.dispatch("reduce")

方法二:使用辅助函数

...mapActions(["asyncAdd"]),
btn2(){
  this.asyncAdd();
}

4.getters: 类似于computed(计算属性,对于Store中的数据进行加工处理形成新的数据-------派生 )

5.modules: 模块拆分

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述