19.使用Vuex进行全局静态管理

1.依赖
npm install vuex --save
2.src下创建目录store
store下创建文件index.js
内容为:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex);
const store = new Vuex.Store({
});
export default store

这样就可以全局使用vuex了
3.使用方式和Vuex.Store中定义的内容有关
State:基础数据

const store = new Vuex.Store({
  state: {
    count: 1
  }
});

组件中引用

{{this.$store.state.count}}

4.Getters:对数据操作后返回

const store = new Vuex.Store({
  state: {
    count: 1
  },
  getters: {
    getStateCount: function (state) {
      return state.count + 1;
    }
  }
});

组件中调用

{{this.$store.getters.getStateCount}}
  1. Mutations:对数据进行操作
const store = new Vuex.Store({
  state: {
    count: 1
  },
  mutations: {
    add(state) {
      state.count = state.count + 1;
    },
    reduce(state) {
      state.count = state.count - 1;
    }
  }
});

组件中调用

//template中
    <div>{{this.$store.state.count}}</div>
    <el-button @click="handleAdd">+</el-button>
    <el-button @click="handleReduce">-</el-button>
//script中
    methods: {
      handleAdd() {
        this.$store.commit("add");
      },
      handleReduce() {
        this.$store.commit("reduce");
      }
    }
  1. Actions:对操作进行封装
    并不建议直接调用Mutations,在Actions中封装Mutations再调用:
  actions:{
    addFunc(context){
      context.commit("add");
    },
    reduceFunc(context){
      context.commit("reduce");
    }
  }

组件中调用

      handleAdd() {
        // this.$store.commit("add");
        this.$store.dispatch("addFunc");
      },
      handleReduce() {
        // this.$store.commit("reduce");
        this.$store.dispatch("reduceFunc");
      }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • vuex 场景重现:一个用户在注册页面注册了手机号码,跳转到登录页面也想拿到这个手机号码,你可以通过vue的组件化...
    sunny519111阅读 12,442评论 4 111
  • 安装 npm npm install vuex --save 在一个模块化的打包系统中,您必须显式地通过Vue.u...
    萧玄辞阅读 7,990评论 0 7
  • Vuex是什么? Vuex 是一个专为 Vue.js应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件...
    萧玄辞阅读 8,299评论 0 6
  • Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应...
    白水螺丝阅读 10,102评论 7 61
  • 目录 - 1.什么是vuex? - 2.为什么要使用Vuex? - 3.vuex的核心概念?||如何在组件中去使用...
    我跟你蒋阅读 9,559评论 4 51