菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
46
0

Vuex的一些常用知识点介绍

原创
05/13 14:22
阅读数 765

一、为什么要使用Vuex

1、多个组件依赖同一个状态,使用组件之间通信方法会非常繁琐,例如多层嵌套组件。

2、需要全局保存的数据,例如用户、权限信息,全局系统设置

二、Vuex的五个核心属性

1、state:存储状态

// store.jsconst store = new Vuex.Store({
  state: {
    count: 0
  }});// 组件里获取count值$store.state.count

2、getters:state作为第一个参数,其他getters作第二个参数,返回值会根据他的依赖缓存起来,相当于Vue的计算属性

// store.jsconst store = new Vuex.Store({
  state: {
    count: 1,
    sum: 2
  },
  getters: {
    getCountAndSum: (state,getters) => {
      return state.count + state.sum;
    }
  }});// 其他组件获取getter$store.getters.getCountAndSum

3、mutations:修改状态(同步的),state 作为第一个参数,提交载荷作为第二个参数

const store = new Vuex.Store({
  state: {
    count: 1 
  },
  mutations: {
    increment (state, obj) {
      state.count += obj.n;
    }
  }});// 其他组件调用mutations的方法$store.commit('increment', {n: 100});

4、actions:异步操作(执行mutations的方法,不是直变更状态)

const store = new Vuex.Store({
  state: {
    count: 1 
  },
  mutations: {
    increment (state, obj) {
      state.count += obj.n;
    }
  },
  actions: {
    increment (context) {
      context.commit('increment');
    }
  }});// 其他组件调用actions的方法$store.dispatch('increment');

5、modules:store的子模块

const a = {
  state: {
    count: 0
  },
  getters: {
    getCount2 (state, getters, rootState) {
      return state.count + 2;
    }
  },
  mutations: {
    increment (state, getters, rootState) {
      state.count++;  
    }
  },
  actions: {
    increment (context) {
      // context.state.count;
      // context.rootState.count;
      context.commit('increment');
    }
  }};const b = {};const store = new Vuex.Store({
  modules: {
     a,
     b  }});// 其他组件调用 (获取state的变量需要加上引入的module的别名)$store.state.a$store.state.b

三、Vuex辅助函数

<template>
  <div class="about">
    <h1>count: <span>{{count}}</span></h1>
    <h1>getCount: <span>{{$store.getters.getCount}}</span></h1>
    <h1>sum: <span>{{sum}}</span></h1>
    <h1>getSum: <span>{{$store.getters.getSum}}</span></h1>
    <button @click="clickB">test    </button>
  </div></template><script>import {mapState, mapGetters, mapMutations, mapActions} from 'vuex'; 
export default {
  name: 'about',
  data () {
    return {
      count: 0,
      sum: 0
    }
  },
  computed: {
    ...mapState({
      count: state => state.count,
      countAlias: 'count',
      countPlusLocalState (state) {
        return state.count + this.localCount;
      }
    }),
    ...mapGetters([
      'getCount', 'getSum'
    ])
  },
  mounted () {
    this.count = this.$store.state.count;
    this.sum = this.$store.state.a.sum;

  },
  methods:{
    ...mapMutations(
      'add','addO'
    ),
    ...mapActions([
      'add','addO'
    ]),
    clickB () {
      this.$store.dispatch('add');
      this.$store.dispatch('addO');
    }
  }
}</script>

发表评论

0/200
46 点赞
0 评论
收藏
为你推荐 换一批