如何将 Vuex store 注入 Vue 3

svo*_*nti 1 javascript vue.js vuex vuejs3 vuex4

我如何将 vuex 注入 Vue 3,在 Vue 2 中可能像:

new Vue({
  el: '#app',
  store: store,
})
Run Code Online (Sandbox Code Playgroud)

但是在 Vue 3 中你会怎么做,因为没有new Vue().

Bou*_*him 5

创建的商店将使用.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)
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请查看Vuex 4 文档

要在选项 api 的子组件中使用它,请尝试按如下方式提供它:

app.use(store)

app.config.globalProperties.$store=store;
Run Code Online (Sandbox Code Playgroud)

然后像$store在子组件中一样使用它

对于组合 api(设置挂钩),您只需导入useStore返回存储实例的可组合函数:

import {useStore} from 'vuex'
setup(){
const store=useStore()// store instead of `$store`


}
Run Code Online (Sandbox Code Playgroud)

  • 是的,您仍然可以像在 vue 2 中一样使用 options api,只需在 main.js 中添加 `app.config.globalProperties.$store=store;` (2认同)