如何在全局创建一个store?
louisscrew opened this issue · 5 comments
louisscrew commented
如何在全局创建一个store?如何像vuex一样创建一个全局的store,例如:
import store from './app/vuex/store.js';//引用store
import router from './app/router/router.js';//引用router
//创建vue实例
window.myvue = new Vue({
el: '#app'
,store:store//把store给root vue
,router:router //通过vue配置中的router挂载router实例
,render: h => h(App)
});
创建一个全局组件后,在每一个组件子组件中都可以通过this.$store来获取这个store。
目前mobx-vue似乎只能针对一个vue创建一个store,子组件不知道用什么方法获取这个呢?
kuitos commented
mobx-vue do not restrict you how to define your store with singleton or multiton, as well as mobx. You could treat any singleton store as global state and import it anywhere.
// xx/store.js
class Store {}
export default new Store()
// App.vue
import store from './xx/store'
class App extends Vue {
store = store;
}
louisscrew commented
ok,我一般比较喜欢单例模式,我在使用vuex和vuet的时候,在创建vue实例的时候就可以传递一个参数,比如store或者其他。之后在其下所有的子组件都可以通过this.$store或者this.$vm.$store的形式就能获取到store。那么对于mobx-vue来讲,是不是子组件也需要如下进行获取store呢?
// xx/store.js
class Store {}
export default new Store()
// App.vue
import store from './xx/store'
import SubComponent from "./SubComponent.vue"
'component-a': ComponentA
@Component({
subComponent:SubComponent
})
class App extends Vue {
store = store;
}
//SubComponent.vue
import store from './xx/store'
class SubComponent extends Vue {
store = store;
}
上面的SubComponent需要引用一次store是吗?
kuitos commented
yep, just import it.
btw, single store is not recommended in mobx paradigm, although not restricted as well. All are up to you.
louisscrew commented
Thank you very much for your answer.
kuitos commented
Feel free to ask any questions!😀