vue.js学习

vuedose.tips(翻译系列八)

2019-10-05  本文已影响0人  知识文青

Two less known facts about Vuex

This tip comes from a special invitee: Nicolò Mezzopera, a web developer on Pulilab and a great person! We even organized a Vue.js meetup in Budapest together this year!

If you happen to be in Verona on April 12th, he’s giving a talk in the Vue Day Italy 2019. It can be your chance to meet him

When using Vuex in our Vue.js components we tend to forget the amazing API that it exposes beside the mapping functions.

让我们看看我们可以做什么,但首先让我们为示例创建一个基本store:

const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    getCountPlusOne: state => state.count + 1
  },
  mutations: {
    increment(state) {
      state.count++;
    }
  }
});

watch方法对于将Vuex与外部代码集成在一起最为有用,无论是在awesomeService中还是在catchAllAuthUtils中。 这是使用方法:

const unsubscribe = store.watch(
  (state, getters) => {
    return [state.count, getters.getCountPlusOne];
  },
  watched => {
    console.log("Count is:", watched[0]);
    console.log("Count plus one is:", watched[1]);
  },
  {}
);

// To unsubscribe:
unsubscribe();

我们正在做的是使用两个函数来调用watch方法,一个函数返回状态和/或我们希望关注的getters的哪一部分,另一个函数是我们要在state.count或getCountPlusOne时调用的函数更改

与React代码,Angular甚至JQuery集成时,这非常有用

See the example inthis CodeSandbox.

有时,与其关注 strore 属性的变化,不如对特定的动作做出反应,记住登录和注销,vuex让我们涵盖了subscribeAction。

调用订阅会添加一个“回调”,该回调在每次操作时都会运行,我们可以用来调用自定义代码

让我们用它在每次 actions 前后启动和停止全局微调器!

const unsubscribe = store.subscribeAction({
  before: (action, state) => {
    startBigLoadingSpinner();
  },
  after: (action, state) => {
    stoptBigLoadingSpinner();
  }
});

// To unsubscribe:
unsubscribe();
上一篇下一篇

猜你喜欢

热点阅读