我什么时候应该使用Vuex? [英] When should I use Vuex?

查看:76
本文介绍了我什么时候应该使用Vuex?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

现在,我开始学习vue,并且正在创建SPA来编辑数据库.现在我不明白应该在哪里使用Vuex.我可以在任何地方使用props和$emit,它可以帮助我找到所需的参数.那么在什么情况下我应该使用Vuex?

Now I start to learn vue, and I'm creating SPA for editing database. Now I can't understand where I should use a Vuex. I can use props and $emit everywhere and it can help me find needed parameter. So for what case I should use Vuex?

推荐答案

根据

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>

这篇关于我什么时候应该使用Vuex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆