![](/img/trans.png)
[英]Vue with Vuex: is it possible to inject/eject components within the store?
[英]How to Inject Vuex store into Vue 3
我如何將 vuex 注入 Vue 3,在 Vue 2 中可能是這樣的:
new Vue({
el: '#app',
store: store,
})
但是在 Vue 3 中你會怎么做,因為沒有new Vue()
。
創建的商店將使用.use
方法注入:
import { createApp } from 'vue'
import { createStore } from 'vuex'
// Create a new store instance.
const store = createStore({
state () {
return {
count: 1
}
}
})
const app = createApp({ /* your root component */ })
// Install the store instance as a plugin
app.use(store)
有關更多詳細信息,請查看Vuex 4 文檔
要在選項 api 的子組件中使用它,請嘗試按如下方式提供它:
app.use(store)
app.config.globalProperties.$store=store;
然后在子組件中像$store
一樣使用它
對於組合 api(設置掛鈎),您可以只導入useStore
組合函數,該函數返回存儲實例:
import {useStore} from 'vuex'
setup(){
const store=useStore()// store instead of `$store`
}
與路由器一起:
import * as Vue from 'vue';
import App from './App.vue';
import router from './routes';
import {store} from "./store/store";
Vue.createApp(App).use(router, store).mount('#app');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.