vuex入门使用详解

1、什么是vuex

Vuex 是实现组件全局状态(数据)管理的一种机制, 可以方便的实现组件之间数据的共享。数据缓存等等

2、vuex的使用


1、安装完vuex依赖后。在项目的src下新建一个store文件夹, 然后再store文件夹下新建一个index.js文件,文件内容如下 import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, getters:{ } }) 2、在main.js中将 store 对象挂载到 vue 实例中 import store from './store/index.js' //..... new Vue({ render: h => h(App), // 将创建的共享数据对象,挂载到 Vue 实例中 // 所有的组件,就可以直接从 store 中获取全局的数据了 store, }).$mount('#app')

 

3.Vuex的核心概念 state、mutation、action、getter
3-1、state
1、创建数据
 export default new Vuex.Store({ 
    state: { num: 0 } 
  })
  
  2、访问数据的第一种方式
  this.$store.state.全局数据名称 
  //访问刚刚创建的num就是 this.$store.state.num
  
  3、访问数据的第二种方式
  // 1. 从 vuex 中按需导入 mapState 函数 
    import { mapState } from 'vuex' 

    //.....

    // 2. 将全局数据,映射为当前组件的计算属性 
    computed: { 
      ...mapState(['num']) 
    }
    
    4、组件绑定响应式
    <template>
      <div id="app">
        <h1>num : {{this.$store.state.num}}</h1>
        <!-- this.$store.state.全局数据名称 -->
        <h1>num : {{num}}</h1>
      </div>
    </template>
    
    <script>
        import { mapState } from "vuex"; //从 vuex 中按需导入 mapState 函数 
        export default {
          name: "App",
          //将全局数据,映射为当前组件的计算属性 
          computed: {
            ...mapState(["num"])
          }
        };
    </script>
3-2、mutation
  1. mutation用于改变store中的数据(state)
  2. 只能通过mutaion改变store数据、不可以直接操作store数据(state)
  3. 通过这种方式虽然操作起来稍微繁琐一些,但是可以集中监控所有数据的变化

1、定义不带参数
export default new Vuex.Store({
  state: { 
    num:0
  },
  mutations: {
    numAddOne(state){
      //num自增1
      state.num++;
    }
  }
})

2、定义带参数
 mutations: {
    //n为参数
    numAddN(state,n){
      //num自增n
      state.num+=n;
    }
  },

3、触发方式和state一样,也有量何种方式
第一种方式
 methods:{
    addOne(){
       this.$store.commit('numAddOne')  //触发 mutations 的第一种方式 
    }
  }
第二种方式
import {mapMutations } from "vuex";//从 vuex 中按需导入 mapMutations 函数

//...

methods:{
    ...mapMutations(['numAddN']),
    // 将指定的 mutations 函数,映射为当前组件的 methods 函数 
  }
4、组件响应式绑定
    <template>
      <div id="app">
        <h1>num : {{this.$store.state.num}}</h1>  <!-- this.$store.state.全局数据名称 -->
        <button @click="addOne">+ 1</button>
        <h1>num : {{num}}</h1>
        <button @click="numAddN(3)">+ n</button>
      </div>  
    </template>
    <script>
    import { mapState ,mapMutations } from "vuex";//从 vuex 中按需导入 mapMutations 函数
    export default {
      name: "App",
      components: {},
      computed: {
        ...mapState(["num"])
      },
      data() {
        return {};
      },
      methods:{
        ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
        addOne(){
           this.$store.commit('numAddOne')  
        }
      }
    };
    </script>

  

3-3 action
  1. Action 用于处理异步任务。
  2. 如果通过异步操作变更数据,必须通过 Action,而不能使用 Mutation,但是在 Action 中还是要通过触发 Mutation的方式间接变更数据。

1、定义不带参数
export default new Vuex.Store({
  state: {
    num: 0
  },
   mutations: {
    numAddOne(state) {
      //num自增1
      state.num++;
    }
  },
  actions: {
    numAddOneAsync(context) {
       setTimeout(() => {
          context.commit('numAddOne') 
        }, 1000) 
      }
  }
})
2、定义带参数
export default new Vuex.Store({
  state: {
    num: 0
  },
  mutations: {
    numAddN(state, n) {
      //num自增n
      state.num += n;
    }
  },
  actions: {
    //n为参数
    numAddNAsync(context,n) {
      setTimeout(() => {
        context.commit('numAddN',n)
      }, 1000)
    }
  }
})
3、触发action的第一种方式
 methods:{
    addOneAsync(){
       this.$store.dispatch('numAddOneAsync')//触发 Action 
    }
  }
4、触发action的第二种方法
//从 vuex 中按需导入 mapActions 函数 
import { mapActions } from 'vuex' 

//.....

//将指定的 actions 函数,映射为当前组件的 methods 函数
methods: { 
  ...mapActions(['numAddNAsync']) 
}

5、组件代码响应式效果
<template>
  <div id="app">
    <h1>num : {{this.$store.state.num}}</h1>  <!-- this.$store.state.全局数据名称 -->
    <button @click="addOne">+ 1</button>
    <br>
     <button @click="addOneAsync">+ 1 Async</button>
    <h1>num : {{num}}</h1>
    <button @click="numAddN(3)">+ n</button>
    <br>
    <button @click="numAddNAsync(3)">+ n Async</button>
  </div>  
</template>

<script>
import { mapState ,mapMutations ,mapActions } from "vuex";//从 vuex 中按需导入 mapXXXX 函数
export default {
  name: "App",
  components: {},
  computed: {
    ...mapState(["num"])
  },
  data() {
    return {};
  },
  methods:{
    ...mapActions(['numAddNAsync']) ,//将指定的 actions 函数,映射为当前组件的 methods 函数 
    ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
    addOne(){
       this.$store.commit('numAddOne')  //触发Mutation
    },
    addOneAsync(){
       this.$store.dispatch('numAddOneAsync')//触发 Action 
    }
  }
};
</script>

  

3-4、getter
  1. Getter 用于对 Store 中的数据进行加工处理形成新的数据。
  2. Getter 可以对 Store 中已有的数据加工处理之后形成新的数据,类似 Vue 的计算属性 。
  3. Store 中数据发生变化,Getter 的数据也会跟着变化。

1、定义getter
export default new Vuex.Store({
  state: {
    num: 0
  },
  getters: {
  	//定义Getter 
    NumText(state ){
      return  '当前的num值为: '+ state.num 
    }
  }
})
2、使用getter的第一种方式
this.$store.getters.名称 //这里就是 this.$store.getters.NumText

3、使用getter的第二种方式
import { mapGetters } from 'vuex' 

 //.....
 
computed: { 
  ...mapGetters(['NumText']) 
}

4、组件响应式数据
    <template>
      <div id="app">
        <h1>{{this.$store.getters.NumText}}</h1>  <!-- this.$store.getters.名称 -->
        <button @click="addOne">+ 1</button>
        <br>
         <button @click="addOneAsync">+ 1 Async</button>
        <h1>{{NumText}}</h1>
        <button @click="numAddN(3)">+ n</button>
        <br>
        <button @click="numAddNAsync(3)">+ n Async</button>
      </div>  
    </template>

    <script>
        import { mapState ,mapMutations ,mapActions,mapGetters  } from "vuex";//从 vuex 中按需导入 mapXXXX 函数
        export default {
          name: "App",
          components: {},
          computed: {
            ...mapState(["num"]),
            ...mapGetters(['NumText']) 
          },
          data() {
            return {};
          },
          methods:{
             ...mapActions(['numAddNAsync']) ,//将指定的 actions 函数,映射为当前组件的 methods 函数 
            ...mapMutations(['numAddN']),// 将指定的 mutations 函数,映射为当前组件的 methods 函数 
            addOne(){
               this.$store.commit('numAddOne')  //触发Mutation
            },
            addOneAsync(){
               this.$store.dispatch('numAddOneAsync')//触发 Action 
            }
          }
        };
    </script>

  

4、模块化module
Module是store分割的模块,每个模块拥有自己的state、getters、mutations、actions。

const moduleA = {
  state: { ... },
  mutations: { ... },
  actions: { ... },
  getters: { ... }
}

const moduleB = {
  state: { ... },
  mutations: { ... },
  actions: { ... }
}

const store = new Vuex.Store({
  modules: {
    a: moduleA,
    b: moduleB
  }
})

store.state.a // -> moduleA 的状态
store.state.b // -> moduleB 的状态

  

  

posted @ 2022-04-25 13:39  小刺猬的大宝贝  阅读(1438)  评论(2编辑  收藏  举报