Vue

Vuex的使用

芸殇
2021-12-15 / 0 评论 / 391 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2024年03月15日,已超过960天没有更新,若内容或图片失效,请留言反馈。

Vuex 是什么?

  Vuex 是一个专门为 Vue 开发的状态管理模式。简单来说,就是 Vue 文件中 data 中的属性,当一个属性需要在多个组件中使用的时候,我们就可以使用 Vuex 来管理这些属性,这样可以让我们减少组件之中反复传值的操作。

应用场景

  一般小项目很少会用到vuex,常规数据放在各个组件内即可,毕竟使用 vuex 的步骤是比较多的。
  一般的公共数据,如:用户信息、token这些可以存放在 vuex 中,最好也在 localstorage 中也存一份,我们在使用这些数据的时候可以先在 vuex 中进行获取如果 vuex 中没有再去 localstorage 中进行获取。
  然后就是在跨多组件传值中可以使用,将数据存放在 vuex 中,这样方便我们取值的同时,也能做到及时响应,一个组件的值发生变化,大家都发生变化。

Vuex 的五个核心概念

  • state:Vuex 中存放属性的。
  • getters:加工 state 中的成员给外界。
  • mutations:修改 state 中的属性的值,同步。
  • actions:异步修改。
  • modules:模块化状态管理。

安装 Vuex

  在项目中使用 npm i vuex -S 进行安装 Vuex ,随后,在目录中创建 store 文件夹,在里面创建 store.js 文件,在 store.js 文件中,使用 import 引入 vue 和 Vuex 。

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

export default new Vuex.Store({
  state: {
    name: Tom,
  },
})

  然后我们需要在 main.js 文件中,将 Vuex 进行挂载。

import store from './store'

new Vue({
  el: '#app',
  router,
  store,  //store:store 和router一样,将我们创建的Vuex实例挂载到这个vue实例中
  render: h => h(App)
})

  这样我们的 Vuex 就挂载到我们的 Vue 项目中了,也就可以使用了。

在组件中使用 Vuex

  我们在组件中需要使用到 Vuex 中的状态时,使用 {{ this.$store.state.name }} 来进行使用,但是这种方式不太推荐。

  <template>
    <div> {{ this.$store.state.name }} </div>
  </template>

  我们可以在 mounted 中或者在computed 中来取 vuex 中的数据

    <template>
      <div> {{ msg }} </div>
    </template>
    <script>
      // 使用 mounted 方式来获取 vuex 数据
      export default {
        data () {
          return {
            msg: ''
          }
        },
        mounted() {
          this.msg = this.$store.state.name
        }
      }

      // 使用 computed 来获取数据
      export default {
        computed() {
          msg() {
            return this.$store.state.name
          }
        }
      }
    </script>

修改 Vuex 中的数据

  使用 action -> mutation -> state 的方式来修改 Vuex 中的数据。
  组件代码:

<template>
  <div>{{ name }}</div>
  <a-button @click="changeNameState">修改名字</a-button>
</template>
<script>
  export default {
    methods: {
      changeNameState() {
        this.$store.dispatch('setStateName')
      }
    },
    computed: {
      name() {
        return this.$store.state.name
      }
    }
  }
</script>

  Vuex 代码

export default new Vuex.Store({
  state: {
    name: 'Tom'
  },
  mutations: {
    // 第一个参数state可以访问到仓库中的state, 第二个参数value则是我们传过来的数据
    SET_NAME: (state, value) => {
      state.name = value
    }
  },
  actions: {
    // 第一个形参store中有一个commit方法,这个参数就是通知 mutations 中的方法该工作了。
    // 第二个参数value,则是我们在组件中用传来的数据
    setStateName(store, value) {
      store.commit('SET_NAME', value)
    }
  },
  // 在这里顺带说一下 getter 的使用,我们可以通过 getter 对 state 中的数据进行加工,来供组件使用
  getters: {
    // 加工state中的数据,state中的数据也会相应改变
    // 在组件中使用 this.$store.getters.otherName 来进行调用
    otherName (state){
      return state.name = 'Jack'
    }
  }
})

辅助函数

  辅助函数是可以让我们在某个组件中需要使用大量 store 中的数据时,可以少写几行代码,可以理解为就是一个语法题。

<template>
  <div>{{ name }}</div>
  <div>{{ age }}</div>
  <div>{{ hight }}</div>
</template>
<script>
// 从 vuex 中引入辅助函数
import { mapState } from 'vuex'
export default {
  // 辅助函数一般搭配计算属性或者方法来进行使用
  computed: {
    // 第一种方式可以通过数组的形式来进行引入
    ...mapState(['name', 'age', 'height'])
    // 第二种方式通过对象的形式来引入,这种方式大多在 vuex 进行模块化后使用
    ...mapState({
      name: state => state.name,
      age: state => state.age,
      height: state => state.height,
    })
  }
}
</script>

  除了 mapState 外辅助函数还有 mapMutations, mapActions, mapGetters 三个,他们的使用方法基本一样在这里就不在多说了。

module 模块化

  模块化的思想还是大而化小、方便后续管理,我们可以将 store 模块化,每一个模块都拥有自己的 state、mutation、action、getter。
  示例代码:

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

// 一般 user 这部分代码是会专门写一个 js 文件然后通过 import 的方式引入到 store 中 index.js 文件里面
const user = {
  state: {
    token: '',
    userName: ''
  },
  mutations: {
    SET_TOKEN: (state, value) => {
      state.token = value
    },
    SET_USER_NAME: (state, value) => {
      state.userName = value
    },
  },
  actions: {
    login(store, value) {
      store.commit('SET_TOKEN', value)
      store.commit('SET_USER_NAME', value)
    }
  }
}

export default new Vuex.Store({
  modules:{
    user
  }
})

  我们在组件中使用模块化的 store 时,需要在 state 和 属性之间加模块名比如:this.$store.state.user.token

0

评论 (0)

取消