且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

我什么时候应该使用Vuex?

更新时间:2022-12-08 10:42:44

根据

According to this awesome tip from Vuedose blog

Vue.js 2.6引入了一些新功能,我真正喜欢的功能是新的全局可观察API.

Vue.js 2.6 introduced some new features, and one I really like is the new global observable API.

现在,您可以在Vue.js组件范围之外创建反应式对象.而且,当您在组件中使用它们时,它将适当地触发渲染更新.

Now you can create reactive objects outside the Vue.js components scope. And, when you use them in the components, it will trigger render updates appropriately.

这样,您可以创建非常简单的存储而无需Vuex,非常适合简单的场景,例如需要在组件之间共享某些外部状态的情况.

In that way, you can create very simple stores without the need of Vuex, perfect for simple scenarios like those cases where you need to share some external state across components.

对于这个小技巧示例,您将构建一个简单的计数功能,将状态外部化到我们自己的商店中.

For this tip example, you’re going to build a simple count functionality where you externalise the state to our own store.

首先创建store.js:

First create store.js:

import Vue from "vue";

export const store = Vue.observable({
  count: 0
});

如果您对突变和操作的想法感到满意,则可以通过创建简单的函数来更新数据来使用该模式:

If you feel comfortable with the idea of mutations and actions, you can use that pattern just by creating plain functions to update the data:

import Vue from "vue";

export const store = Vue.observable({
  count: 0
});

export const mutations = {
  setCount(count) {
    store.count = count;
  }
};

现在,您只需要在组件中使用它即可.要访问状态,就像在Vuex中一样,我们将使用计算出的属性和方法进行突变:

Now you just need to use it in a component. To access the state, just like in Vuex, we’ll use computed properties, and methods for the mutations:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <button @click="setCount(count + 1);">+ 1</button>
    <button @click="setCount(count - 1);">- 1</button>
  </div>
</template>

<script>
  import { store, mutations } from "./store";

  export default {
    computed: {
      count() {
        return store.count;
      }
    },
    methods: {
      setCount: mutations.setCount
    }
  };
</script>