vue(22)Vuex的安装与使用

前言

每一个 Vuex 应用的核心就是 store(仓库)。store基本上就是一个容器,它包含着你的应用中大部分的状态 (state)Vuex 和单纯的全局对象有以下两点不同:

  1. Vuex 的状态存储是响应式的。当 Vue 组件从 store 中读取状态的时候,若 store 中的状态发生变化,那么相应的组件也会相应地得到高效更新。
  2. 你不能直接改变 store 中的状态。改变 store 中的状态的唯一途径就是显式地提交 (commit) mutation。这样使得我们可以方便地跟踪每一个状态的变化,从而让我们能够实现一些工具帮助我们更好地了解我们的应用。
     

Vuex的安装

安装通过NPM命令:

npm install vuex --save

在一个模块化的打包系统中,您必须显式地通过 Vue.use() 来安装 Vuex

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

如果我们使用vue-cli创建项目并选择配置了Vuex,那么项目会自动给我们配置好这些
 

Vuex的简单示例

安装 Vuex 之后,我们需要在某个地方存放我们的Vuex代码
这里我们先创建一个文件夹store,并且在其中创建一个index.js文件,在文件中写入如下代码

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    counter: 1000,
  },
  mutations: {
    increment(state) {
      state.counter++;
    },
    decrement(state) {
      state.counter--;
    },
  },
});

其次,我们让所有的Vue组件都可以使用这个store对象,来到main.js文件中,导入store对象,并且放在new Vue中,这样其他Vue组件中,我们就可以通过this.$store的方式,获取到这个store对象

import Vue from "vue";
import App from "./App.vue";
import store from "./store";

new Vue({
  store,
  render: (h) => h(App),
}).$mount("#app");

然后在App.vue中写入如下代码:

<template>
  <div id="app">
    <h2>{{ $store.state.counter }}</h2>
    <button @click="addMethod">+</button>
    <button @click="reduce">-</button>
  </div>
</template>

<script>
export default {
  name: "App",
  methods: {
    addMethod() {
      this.$store.commit("increment");
    },
    reduce() {
      this.$store.commit("decrement");
    },
  },
};
</script>
<style lang="scss"></style>

 

Vuex使用步骤总结

  • 1.提取一个公共的store对象,用于保存多个组件中共享的状态

  • 2.将store对象放置在new Vue对象中,这样可以保证在所有的组件中都可以用到

  • 3.在其他组件中使用store对象中保存的状态即可

    • 通过this.$store.state属性的方式来访问状态
    • 通过this.$store.commit("mutations中的方法")来修改状态
  • 注意事项

    • 我们是通过提交mutations的方式,而非直接改变store.state.counter
    • 这是因为Vuex可以更明显的追踪状态的变化,所以不要直接改变store.state.counter的值
       
Tags: