为了账号安全,请及时绑定邮箱和手机立即绑定

Vue 中全局单例的使用?

Vue 中全局单例的使用?

波斯汪 2023-04-27 10:52:01
我想将我的行为集中在定义如下的模型中:class Foobar {    doit() {        console.log('I am doing it');    }}let foobar = new Foobar()const app = new Vue({   store,    router,    foobar,   ...})稍后,在一个子组件中,我想在我的模型上触发一个动作,我想这样做:<template>   <b-button @click="doit">Do It</b-button></template><script>export default {    methods: {        doit() {           this.$foobar.doit(); // <----        }    }}</script>那里似乎$foobar无法访问。Vue 中将操作集中在外部单例中的正确方法是什么?
查看完整描述

1 回答

?
森林海

TA贡献2011条经验 获得超2个赞

您可以这样做,但我不确定数据的持久性如何。


Vue.prototype.$foobar = foobar;

使用 Vuex 可能会更好,因此它通过应用程序持久化。


店内:


const state = {

 foobar: Foobar

}

const mutations = {

 initialize (state) {

   state.foobar = new Foobar();

  }

}

在 main/app.js 里面:


store.commit('initialize')


查看完整回答
反对 回复 2023-04-27
  • 1 回答
  • 0 关注
  • 65 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信