基本上我想在 vue install 中使用我自己的商店,并通过 vue 插件添加 vue 组件。
我发现我可以在实际安装函数中使用 vuex 并执行 vuex 可以执行的所有操作,但我似乎无法将其传递给我的自定义组件。
是否有其他方法可以在我的插件中添加的 SFC 中添加全局事件?
import MyComponent from './MyComponent.vue'
import MySecondComponentfrom './MySecondComponent.vue'
import Vuex from 'vuex'
import store from './store.js'
const CustomFn = function(message, options) {
this.$store.dispatch("someRandomAction", { message, options })
}
export default {
install(Vue, options) {
if (this.installed) { return }
this.installed = true
Vue.use(Vuex)
const storeInstance = new Vuex.Store(store)
Vue['store'] = storeInstance
// is there a way to add storeInstance to my own components and share one state between them?
Vue.component('MyComponent', Vue.extend(MyComponent))
Vue.component('MySecondComponent', Vue.extend(MySecondComponent))
Vue.prototype['$doStuff'] = CustomFn
Vue['doStuff'] = CustomFn
}
}
问题是我无法在 MyComponent 内传递此 Vuex 存储实例并在多个组件之间共享相同的存储。
最佳答案
自定义组件属性应该在 Vue 2 中通过将其分配给 Vue.prototype
来全局提供,因为组件实例通常继承自它。
store
已经是 Vuex 存储而不是包含存储选项的普通对象,则 new Vuex.Store(store)
是一个错误。这将导致存储出现故障,如 this question 所示。 。即使 store
还不是存储实例,将其设为实例并在单独的模块中导出也是有意义的,以便可以在非组件模块中导入它。
应该是:
Vue.prototype.$store = store
关于javascript - 有没有办法将 Vuex 添加到 Vue 插件安装功能并在其组件之间共享状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70816511/