安装
本体
npm install pinia
vue2特定
npm install @vue/composition-api
持久化存本地
npm install pinia-plugin-persist
vue.config.js
不加的话会报错
configureWebpack: {
// 在configureWebpack里加上以下module
module: {
rules: [
{
test: /\.mjs$/,
include: /node_modules/,
type: "javascript/auto"
}
]
},
}
main.js
import { createPinia, PiniaVuePlugin } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'
Vue.use(PiniaVuePlugin)
const pinia = createPinia() //需要挂载在实例上
pinia.use(piniaPluginPersist) // 持久化本地存储
new Vue({
el: '#app',
router,
store,
pinia, // 这里
created: bootstrap,
render: h => h(App)
})
store文件夹下新建news.js
import { defineStore } from 'pinia'
export const useCounterStore = defineStore('counter', {
persist: {
enabled: true, // 开启本地存储
strategies: [
{
key: 'count',
storage: localStorage
}
]
},
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
decrement() {
this.count--;
},
},
});
在vue文件中使用
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
<button @click="decrement">Decrement</button>
</div>
</template>
<script>
import { useCounterStore } from '@/store/news.js'
export default {
computed: {
count() {
return useCounterStore().count;
},
},
methods: {
increment() {
useCounterStore().increment();
},
decrement() {
useCounterStore().decrement();
},
},
}
</script>