猿问

vue.js:在实现“从头开始的简单状态管理”方法时,如何传递/访问存储?

这可能是一个非常愚蠢的问题,但是在阅读了vue.js 的状态管理文档之后,我想尝试一下 store 模式。

我注意到store.state示例中的两个应用程序之间共享。但是我现在如何setMessageAction从组件中调用 store 的方法呢?商店不应该以某种方式注入/注册到 vue 实例中,以便可以通过this组件或类似的东西访问吗?



繁星coding
浏览 91回答 1
1回答

江户川乱折腾

是的,你是对的。您应该在组件声明中声明您的商店,如此处所述document.jsvar store = {&nbsp; &nbsp; debug: true,&nbsp; &nbsp; state: {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; message: 'Hello!'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;},&nbsp; &nbsp; setMessageAction (newValue) {&nbsp; &nbsp; &nbsp; &nbsp; if (this.debug) console.log('setMessageAction triggered with', newValue)&nbsp; &nbsp; &nbsp; &nbsp; this.state.message = newValue&nbsp; &nbsp; },&nbsp; &nbsp; clearMessageAction () {&nbsp; &nbsp; &nbsp; &nbsp; if (this.debug) console.log('clearMessageAction triggered')&nbsp; &nbsp; &nbsp; &nbsp; this.state.message = ''&nbsp; &nbsp; }&nbsp;}var vmA = new Vue({&nbsp; &nbsp;data: {&nbsp; &nbsp; privateState: {},&nbsp; &nbsp; <!-- HERE YOU ARE PASSING THE STATE -->&nbsp; &nbsp; sharedState: store.state&nbsp; &nbsp; }&nbsp; })
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答