[英]How to Inject Vuex store into Vue 3
How would I inject vuex into Vue 3, in Vue 2 it was possible like:我如何将 vuex 注入 Vue 3,在 Vue 2 中可能是这样的:
new Vue({
el: '#app',
store: store,
})
But in Vue 3 how would you do it since there is no new Vue()
.但是在 Vue 3 中你会怎么做,因为没有
new Vue()
。
The created store will be injected using .use
method :创建的商店将使用
.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)
For more details check the Vuex 4 docs有关更多详细信息,请查看Vuex 4 文档
To use it in child component in options api, try to provide it as follows :要在选项 api 的子组件中使用它,请尝试按如下方式提供它:
app.use(store)
app.config.globalProperties.$store=store;
then use it like $store
in child components然后在子组件中像
$store
一样使用它
for composition api (setup hook), you could just import the useStore
composable function which returns the store instance :对于组合 api(设置挂钩),您可以只导入
useStore
组合函数,该函数返回存储实例:
import {useStore} from 'vuex'
setup(){
const store=useStore()// store instead of `$store`
}
Together with Router:与路由器一起:
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.