美文网首页
19.使用Vuex进行全局静态管理

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

作者: 面具猴 | 来源:发表于2019-06-11 11:17 被阅读0次

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");
      }

相关文章

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

    1.依赖npm install vuex --save2.src下创建目录storestore下创建文件index...

  • C++——静态成员函数与静态成员变量

    静态成员函数与静态成员变量使用static进行定义。 静态成员函数和静态成员变量其实就是全局函数与全局变量。 静态...

  • C++——静态成员函数与静态成员变量

    静态成员函数与静态成员变量使用static进行定义。 静态成员函数和静态成员变量其实就是全局函数与全局变量。 静态...

  • vuex

    VUEX的使用 vuex的作用: 常用来作为全局状态管理器, 定义一个状态全局可用,部分功能与缓存类似,但是vue...

  • 学习vue2.0笔记(第五章下)

    状态管理插件vuex 状态管理机制 安装 import导入,注册,实例化, 全局使用store, 通过this.$...

  • 如何管理 vue 项目中的数据?

    vuex 如何管理 vue 项目的数据?这个问题似乎早已经有答案了,无非就是使用 vuex ,全局 store,整...

  • 如何管理 vue 项目中的数据?

    vuex 如何管理 vue 项目的数据?这个问题似乎早已经有答案了,无非就是使用 vuex ,全局 store,整...

  • Vuex

    Vuex简介: 由于使用propes传递数据太麻烦,所以使用vuex进行状态管理。不能直接修改vuex中的数据,只...

  • Vuex

    1.Vuex概述 2.Vuex基本使用 3.使用Vuex完成todo案例 1.Vuex概述 Vuex是实现组件全局...

  • 2020常见vue面试题

    什么是vuex?在那种场景下使用? vuex是全局状态管理工具,它有以下几个核心部分组成: state:存储数据;...

网友评论

      本文标题:19.使用Vuex进行全局静态管理

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