【vuex】一个例子理解

Vuex 实现了一个单项数据流,通过创建一个全局的 State 实例,来实现数据保存和变更

类似于写线程池的时候,有一种思路是提供一段公共内存,里边的确定一些数据,在各个线程中流转变化,当然线程使用里有线程锁的概念,防止同一时段,不同线程改同一数据,造成数据污染,这里就不多谈了

PS:关于线程锁,node中worker_threads的解决方法:

每个线程单独copy出来一份数据,最后单个返回改变之后的数据,原有的数据并没有变化

页面上的操作想要修改 State 数据时,需要通过 Dispatch (触发 Action ),

而 Action 也不能直接操作数据,还需要通过 Mutation 来修改 State 中数据,

最后根据 State 中数据的变化,来渲染页面。

总之:

组件想要修改 State 数据只能通过 Mutation 来进行,

(1)main.js中引入store


import Vue from 'vue';
import Tpl from './index.vue';
import store from './store';

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

(2)store.js的实现

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

Vue.use(Vuex);

//创建的store实例

const store = new Vuex.Store({
 //要改变的数据原型  

 state: {
    count: 1
  },

 //state发生变化的根本方法  
  mutations:
{
    increment(state) {
      state.count++;
    },
    reduce(state) {
      state.count--;
    }
  },

  //mutations的异步触发
  actions:
{
    actIncrement({ commit }) {
      commit('increment');
    },
    actReduce({ commit }) {
      commit('reduce');
    }
  },

  //相当于计算属性
  getters: {
    doubleCount: state => state.count*2
  }
});

export default store;

(3)使用

// vue文件
<template>
  <div class="container">
    <p>我的count:{{count}}</p>
    <p>doubleCount:{{doubleCount}}</p>
    <button @click="this.actIncrement">增加</button>
    <button @click="this.actReduce">减少</button>
  </div>
</template>

<script>

//解构出我们需要用到的部分
import { mapGetters, mapActions, mapState } from "vuex";

export default {
  name: "demo",
  data: function() {
    return {};
  },
  components: {},
  props: {},

  //state和getter的值放在计算属性里防止刷新消失,通过数组展开
  computed: {
    ...mapState(["count"]),
    ...mapGetters(["doubleCount"])
  },

  //把actions里边的内容展开为本实例方法,通过数组展开
  methods: {
    ...mapActions(["actIncrement", "actReduce"])
  }
};
</script>

发布了283 篇原创文章 · 获赞 21 · 访问量 20万+

猜你喜欢

转载自blog.csdn.net/dangbai01_/article/details/102900835