【问题标题】:Access app.config.globalProperties in vuex store在 vuex 商店中访问 app.config.globalProperties
【发布时间】:2021-09-24 16:40:44
【问题描述】:

我有一个像这样的 vuex 商店:

const state = {
    status: '',
};

const getters = {
   //...
};

const actions = {

 // ...
};

const mutations = {
// ... 
};

export default {
    namespaced: true,
    state,
    getters,
    actions,
    mutations,
}

现在我想访问app.config.globalProperties.$notify

在 Vue.js2 中,我使用了 Vue.prototype.$notify 之类的东西,但这不再起作用了。

$notify 也是这样提供的:

app.use(routes)
  .provide('notify', app.config.globalProperties.$notify)
  .mount('#app')

很遗憾,我还没有在文档中找到任何相关信息。

所以我的问题是:如何在这家商店中注入 $notify 或访问 app.config.globalProperties

【问题讨论】:

  • 实例可用this._vm
  • this._vmundefined :-/
  • 您是如何访问它的?它应该在 Vuex 的常规函数​​中定义,而不是箭头。
  • 我在尝试 ``` // ... const mutation = { test (state, {committedItem}) { //... console.log(this._vm) //undefined }, }; export default { namespaced: true, state, getters, actions, mutation, } ```

标签: vue.js vuex vuejs3 vuex4


【解决方案1】:

从您的商店及其模块中,您可以返回一个商店工厂——一个从createApp 接收应用程序实例并返回商店的函数:

// store/modules/my-module.js
const createStore = app => {
  const mutations = {
    test (state, { committedItem }) {
      app.config.globalProperties.$notify('commited item: ' + committedItem)
    }
  }

  return {
    namespaced: true,
    //...
    mutations,
  }
}

export default app => createStore(app)
// store/index.js
import { createStore } from 'vuex'
import myModule from './modules/my-module'

export default app =>
  createStore({
    modules: {
      myModule: myModule(app)
    }
  })

然后像这样使用 store 工厂:

// main.js
import { createApp } from 'vue'
import App from './App.vue'
import createStore from './store'

const app = createApp(App)
app.use(createStore(app)).mount('#app')

demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-02-05
    • 2020-12-07
    • 2020-05-22
    • 2017-12-05
    • 2021-10-20
    • 2020-08-21
    • 2018-05-19
    • 2018-12-19
    相关资源
    最近更新 更多