编程知识 cdmana.com

预填充Vue.js全局存储状态的三种方法

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","marks":[{"type":"italic"}],"text":"本文最初发布于austingil.com网站,经原作者授权由InfoQ中文站翻译并分享。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"在构建Vue.js应用程序时,当这些应用程序的规模扩张到一定程度后,你就可能会遇到管理全局状态的需求了。还好,他们的核心开发团队提供了Vuex这个便利的工具,这是Vue.js应用程序状态管理库的事实标准。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"要入门这个库非常简单,所以我假设你已经熟悉了Vuex的实现。这篇文章并不是一篇入门教程。如果你需要从头开始了解的话,那么我建议你查阅"},{"type":"link","attrs":{"href":"https:\/\/vuex.vuejs.org\/","title":"","type":null},"content":[{"type":"text","text":"文档"}]},{"type":"text","text":"。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"Vuex让我们可以更方便地管理全局数据存储。对于下面的示例,假设我们有一个看起来像这样的存储:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"text"},"content":[{"type":"text","text":"import Vue from 'vue'\nimport Vuex from 'vuex'\nVue.use(Vuex)\nconst store = new Vuex.Store({\n state: {\n user: null\n },\n mutations: {\n setUser (state, user) {\n state.user = user\n }\n },\n})\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"这个存储的初始状态有一个空的user对象,以及一个可以更新状态的setUser突变。然后,在我们的应用程序中,我们可能想要显示user的详细信息:"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"text"},"content":[{"type":"text","text":"