在 Vue 2 中使用 Pinia 的 mixin 可以参照以下方式:
- 在
main.js
中创建和注册 Pinia 实例,代码如下:
import Vue from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
const pinia = createPinia()
Vue.use(pinia)
new Vue({
el: '#app',
pinia,
render: h => h(App)
})
这里我们创建了一个名为 pinia
的 Pinia 实例,并在 Vue 中注册,然后将实例作为参数传递给 Vue 实例。
- 在 mixin 中使用
this.$pinia
访问到 Pinia 实例:
import { useCounterStore } from './store/counter'
export const counterMixin = {
computed: {
count() {
const store = useCounterStore()
return store.count
}
},
methods: {
increment() {
const store = useCounterStore()
store.increment()
}
}
}
在上述代码中,我们可以在 mixin 中通过 useCounterStore
方法来获取到 counter
Store 的实例,从而访问到 Store 中的状态和方法。注意,在 Vue 2 中,在 mixin 中不能像在 Vue 3 中那样通过 inject
和 provide
来实现依赖注入,因此需要在每个函数中都获取 Store 实例。
最后,在组件的选项对象中引入 mixin 即可使用。
希望以上内容能够帮助你在 Vue 2 中成功使用 Pinia。