【vuex】一个例子理解Vuex

Vuex的本质

Vuex的本质是一个没有template的组件,state说白了就是data,

mutations是同步改变data

actions是异步改变data

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>

PS:直接使用

直接在组件中使用:

this.$store.state.xxx;

this.$store.commit("xxx",params); //params可选,需要

this.$store.dispatch("xxx",params)

1.actions定义的部分,可以不用解构,直接使用context

2.mutations可以不用,都写成actions,本质上就是改state,或者说无template组件的data而已

eg:

    actions:{
        testActions(context,extro){
            //context里边包含了state,mutation,getters,actions
            //相当于异步请求得到值,然后在视图中显示值
            setTimeout(()=>{
                context.state.testList = ["1","2","3","4"];
                console.log(extro);
            },2000);
            
        }
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值