Vuex最新使用说明详解

作者: 飞天小猪_pig | 来源:发表于2022-09-02 23:58 被阅读0次

    Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库,简单一点理解就是为了可以实现组件之间实现相互共享数据这需求。

    以下代码实现可以在CodeSandbox实现

    一、基本用法:
    import { createApp } from 'vue'  //引入vue
    import App from './App.vue'    //APP组件
    import {createStore} from 'vuex'  //引入vuex
    
    const app=createApp(App)  //创建vue实例
    app.mount('#app')    //将vue实例挂载到HTML中id为app的标签中
    
    const store=createStore({    //创建vuex的实例
      state(){     
         return{
           count:0
         }
      },
      mutations:{    
        increment(state){
          state.count++
        }
      }
    })
    
    app.use(store)    //将创建实例store挂载到vue实例上
    

    (1)、 直接调用如下:

    store.commit('increment')   //store.commit 方法触发状态变更
    console.log(store.state.count)    //store.state 来获取状态对象
    

    (2)、在 Vue 的组件中调用, 可以通过 this.$store 访问store实例。现在我们可以从组件的方法提交一个变更:

    methods: {
      add() {
        this.$store.commit('increment')  //store.commit 方法触发状态变更
        console.log(this.$store.state.count)   //store.state 来获取状态对象
      }
    }
    
    二、核心概念使用

    (1)、state :包含了store中存储的数据各个状态(初始化数据地方)。

    const store=createStore({    //创建vuex的实例
      state(){     
         return{
           count:0
         }
      },
    })
    

    //直接调用
    store.state.count //store.state 来获取状态对象

    //在组件中调用
    this.$store.state.count //this.$store.state 来获取状态对象

    一般来说不这样直接获取状态对象数据,通常都是通过getter方法获取

    (2)、getter: 类似于 Vue 中的计算属性,getters根据state或者其他getters计算出另一个变量的值,当其依赖的数据变化时候,它也会实时更新。

    getter 接受 state 作为其第一个参数,也可以接受其他 getter 作为第二个参数

    const store=createStore({
      state: {
        todos: [
          { id: 1, text: '...', done: true },
          { id: 2, text: '...', done: false }
        ]
      },
      getters: {
        doneTodos (state) {
          //在getters中对state数据进行处理,后面就可以通过getters接口间接获取state数据
          return state.todos.filter(todo => todo.done)   
        }
      }
    })
    

    方法一:

    //直接调用
    console.log(store.getters.doneTodos) //store.getters 来间接获取状态对象

    方法二:

    //在组件中调用
    console.log(this.$store.getters.doneTodos) //this.$store.getters 来间接获取状态对象

    方法三:

    在组件中还可以通过mapGetters 辅助函数利用computed函数间接获取状态对象

    import { mapGetters } from 'vuex'   //必须从vuex中引入mapGetters函数
    
    export default {
      // 组件其他代码省略
      computed: {    // 使用对象展开运算符将 getter 混入 computed 对象中
        ...mapGetters([     //  ...mapGetters函数映射
          'doneTodos ',     //这个doneTodos 是getter定义方法
          'anotherdoneTodos ',   //这个anotherdoneTodos 也是getter定义方法
        ])
      }
    }
    

    如果你想将一个 getter 属性另取一个名字,使用对象形式:

    ...mapGetters({
      // 把 `this.doneCount` 映射为 `this.$store.getters.doneTodos `
      doneCount: 'doneTodos '
    })
    

    总结mapGetters辅助函数适合用于getter定义了许多方法,在组件调用时候不想一个一个写this.$store.getters来间接获取状态对象,就可以通过辅助函数全部映射过组件直接调用映射后名字即可。

    (3)、mutation: 同步执行,是改变store中状态的执行者,简单一点就是通过提交mutation来改变state中的数据。

    1、只有state一个参数

    const store = createStore({
      state: {
        count: 1
      },
      mutations: {
        increment (state) {
          state.count++  // 变更状态
        }
      }
    })
    

    2、带载荷(payload),也就是第二参数,由组件传进来的,多数情况下payload都是一个对象。

    const store = createStore({
      state: {
        count: 1
      },
      mutations: {
        increment (state,payload) {
          state.count += payload.amount  // 变更状态
        }
      }
    })
    

    方法一:

    //直接调用
    store.commit('increment') //通过store.commit 触发mutation事件
    store.commit('increment', {amount: 10}) //带payload情况,触发事件

    方法二:

    //在组件中调用
    this.$store.commit('increment') //通过this.$store.commit 触发mutation事件。

    this.$store.commit('increment', {amount: 10}) //带payload情况,触发事件

    方法三:
    在组件中还可以通过mapMutations 辅助函数通过映射利用methods方法

    import { mapMutations } from 'vuex'
    
    export default {
      methods: {
        ...mapMutations([
          'increment', // 将 `this.increment()` 映射为 `this.$store.commit('increment')`
    
          // `mapMutations` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为     `this.$store.commit('incrementBy', amount)`
        ]),
      }
    }
    

    (4)、action: 异步方法,action并不直接改变state,而是提交触发mutation从而改变state状态。

    const store = createStore({
      state: {
        count: 0
      },
      mutations: {
        increment (state) {
          state.count++
        }
      },
      actions: {
        increment (context) {
          context.commit('increment')
        }
      }
    })
    

    方法一:

    //直接调用
    store.dispatch('increment') //store.dispatch触发mutation事件
    store.dispatch('increment', {amount: 10}) //带payload情况,触发事件

    方法二:

    //在组件中调用
    this.$store.dispatch('increment') // store.dispatch触发mutation事件。

    this.$store.dispatch('increment', {amount: 10}) //带payload情况,触发事件

    方法三:
    在组件中还可以通过mapActions 辅助函数通过映射利用methods方法

    import { mapActions } from 'vuex'
    
    export default {
      methods: {
        ...mapActions([
          'increment', // 将 `this.increment()` 映射为 `this.$store.dispatch('increment')`
    
          // `mapActions` 也支持载荷:
          'incrementBy' // 将 `this.incrementBy(amount)` 映射为 `this.$store.dispatch('incrementBy', amount)`
        ]),
      }
    }
    

    (5)、module模块
    当应用变得非常复杂时,store 对象就有可能变得相当臃肿。为了解决以上问题,将 store 分割成模块(module)。每个模块拥有自己的 state、mutation、action、getter、甚至是嵌套子模块——从上至下进行同样方式的分割:

    const moduleA = {
      state: () => ({ ... }),
      mutations: { ... },
      actions: { ... },
      getters: { ... }
    }
    
    const moduleB = {
      state: () => ({ ... }),
      mutations: { ... },
      actions: { ... }
    }
    
    const store = createStore({
      modules: {
        a: moduleA,
        b: moduleB
      }
    })
    
    store.state.a // -> moduleA 的状态
    store.state.b // -> moduleB 的状态
    

    相关文章

      网友评论

        本文标题:Vuex最新使用说明详解

        本文链接:https://www.haomeiwen.com/subject/npaenrtx.html