我应该什么时候使用 Vuex? [英] When should I use Vuex?
问题描述
现在我开始学习vue,我正在创建用于编辑数据库的SPA.现在我不明白我应该在哪里使用 Vuex.我可以在任何地方使用 props 和 $emit
,它可以帮助我找到所需的参数.那么在什么情况下我应该使用 Vuex?
根据 这个很棒的技巧
来自 Vuedose 博客
Vue.js 2.6 引入了一些新功能,其中我非常喜欢的是新的全局可观察 API.
现在您可以在 Vue.js 组件范围之外创建反应式对象.并且,当你在组件中使用它们时,它会适当地触发渲染更新.
这样,您无需 Vuex 即可创建非常简单的存储,非常适合简单的场景,例如需要跨组件共享某些外部状态的情况.
对于这个技巧示例,您将构建一个简单的计数功能,将状态外部化到我们自己的商店.
首先创建 store.js:
从vue"导入Vue;export const store = Vue.observable({计数:0});
如果您对突变和操作的想法感到满意,您可以通过创建简单的函数来更新数据来使用该模式:
从vue"导入Vue;export const store = Vue.observable({计数:0});导出常量突变 = {设置计数(计数){store.count = 计数;}};
现在你只需要在一个组件中使用它.要访问状态,就像在 Vuex 中一样,我们将使用计算属性和用于更改的方法:
<div><p>计数:{{计数}}</p><button @click=setCount(count + 1);">+ 1</button><button @click=setCount(count - 1);">- 1</button>
模板><脚本>从./store"导入{存储,突变};导出默认{计算:{数数() {返回 store.count;}},方法: {setCount:mutations.setCount}};
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 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>
这篇关于我应该什么时候使用 Vuex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!