我什么时候应该使用 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 中一样,我们将使用计算属性和突变方法:
<模板><p>计数:{{ count }}</p><按钮@click="setCount(count + 1);">+1</button><按钮@click="setCount(count - 1);>- 1</button></div></模板><脚本>从./store"导入{ store,mutations };导出默认{计算:{数数() {返回 store.count;}},方法: {setCount: 突变.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>
相关文章