vuex的基础知识点

时间:2022-07-25
本文章向大家介绍vuex的基础知识点,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

vuex的基础知识点

1 安装与引用

引用:npm install vuex --save

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)

2 核心概念

state:vuex的基本数据,用来存储变量,可以实现多个组件都可以访问在这个变量,通常将全局数据将保存在这里。

state: {
  counter:1000
},

//在组件中访问
computed:{
  count() {
    return this.$store.state.counter
  }
},

geeter:从基本数据(state)派生的数据,相当于state的计算属性,有些时候我们需要从store中的state中返回特定的模板或者计算,这个时候我们就需要用到Getter

<template>
  <div id="app">{{print}}</div>
</template>

<script>

export default {
  data(){
    return {
      print: this.$store.getters.print
    }
  }
};
</script>

mutation:提交更新数据的方法,必须是同步的(如果需要异步使用action)。每个 mutation 都有一个字符串的 事件类型 (type) 和 一个 回调函数 (handler)。回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数,提交载荷作为第二个参数。

// vue
<template>
  <div id="app">{{userinfo}}<button @click="setage">修改</button></div>
</template>

<script>
import { mapState, mapGetters, mapMutations } from "vuex";

export default {
  methods:{
    ...mapMutations(['changeAge']),
    setage(){
      this.changeAge([20])
    }
  },
  computed: {
    ...mapGetters({
      userinfo: "print"
    })
  }
};
</script>

action:和mutation的功能大致相同,不同之处在于 ==》1. Action 提交的是 mutation,而不是直接变更状态。 2. Action 可以包含任意异步操作。

// store/index/js
export default new Vuex.Store({
    state: {
        msg: 'hello world',
        name: 'rabbit',
        age: 18
    },
    getters: {
        print(state) {
            return `姓名:${state.name} 年龄:${state.age}`
        }
    },
    mutations: {
        changeAge(state, payload) {
            state.age = payload[0]
        }
    },
    actions: {

    },
    modules: {

    }
})
<template>
  <div id="app">{{userinfo}}<button @click="setage">修改</button></div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";

export default {
  methods:{
    ...mapActions(['asychangeAge']),
    setage(){
      this.asychangeAge([18]).then(() => {
        console.log('修改完成')
      })
    }
  },
  computed: {
    ...mapGetters({
      userinfo: "print"
    })
  }
};
</script>

modules:模块化vuex,可以让每一个模块拥有自己的state、mutation、action、getters,使得结构非常清晰,方便管理。

export default new Vuex.Store({
  // ......
  modules: {
      moduleA: {
          namespaced: true,
          state: {
              name: 'moduleA'
          },
          getters: {},
          mutations: {
              changeName(state, payload) {
                  console.log(payload)
                  state.name = payload
              }
          },
          actions: {
              asychangeName({ commit }, payload) {
                  commit('changeName', payload);
              }
          }
      },
      moduleB: {
          namespaced: true,
          state: {
              name: 'moduleB'
          },
          getters: {},
          mutations: {
              changeName(state, payload) {
                  console.log(payload)
                  state.name = payload
              }
          },
          actions: {
              asychangeName({ commit }, payload) {
                  commit('changeName', payload);
              }
          }
      },
  }
})
<template>
  <div id="app">
    {{moduleA}}
    <br />
    {{moduleB}}
    <br />
    <button @click="setage">修改</button>
  </div>
</template>

<script>
import { mapState, mapGetters, mapMutations, mapActions } from "vuex";

export default {
  methods: {
  	// 收集并重命名模块A中的Action
    ...mapActions("moduleA", {
      asychangeModuleA: "asychangeName"
    }),
  	// 收集并重命名模块B中的Action
    ...mapActions("moduleB", {
      asychangeModuleB: "asychangeName"
    }),
    setage() {
  	  // 修改模块A中的数据
      this.asychangeModuleA("This is the value of moduleA I modified").then(() => {
        console.log("修改moduleA成功");
      });
  	  // 修改模块B中的数据
      this.asychangeModuleB("This is the value of moduleB I modified").then(() => {
        console.log("修改moduleB成功");
      });
    }
  },
  computed: {
  	// 收集并重命名模块A中的State
    ...mapState("moduleA", {
      moduleA: state => state.name
    }),
  	// 收集并重命名模块B中的State
    ...mapState("moduleB", {
      moduleB: state => state.name
    })
  }
};
</script>