且构网

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

我什么时候应该使用 Vuex?

更新时间:2022-12-08 10:34:09

According to this awesome tip from Vuedose blog

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

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.

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.

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;
  }
};

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>

相关阅读

技术问答最新文章