//main.js
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
// import store from './store'
import {createPinia} from 'pinia'
// 安装pinia插件实现持久化存储,根据需求安装,不需要则不用安装
// npm i pinia-plugin-persist --save
// 引入插件
import piniaPluginPersist from 'pinia-plugin-persist'
// 使用插件
const pinia = createPinia()
pinia.use(piniaPluginPersist)
createApp(App).use(pinia).use(router).mount('#app')
// store/index.js
import { defineStore } from 'pinia'
export const useStore = defineStore('storeId',{
//类似data
state: ()=>{
return {
num:1,
name:'张三',
arr:[],
count:0
}
},
//类似计算属性
getters: {
changeNum(){
return this.num +100
}
},
//类似方法
actions: {
upNum(val){
this.num +=val
},
addarr(obj){
this.arr.push(obj)
this.count = this.arr.length
}
},
//开启数据缓存,不需要则不用下方代码
persist:{
enabled:true,
strategies:[
{
key:'my_user',//储存的key
storage:localStorage,//储存方式
paths:['num']//储存数据,不要此项则储存所有数据
}
]
}
})
//vue页面
<template>
<div class="hello">
{{msg}}
</div>
<div>
{{name}}------{{num}}
<br>
<button @click="btn">按钮</button>
<br>
<button @click="addbtn">add</button>
<br>
{{changeNum}}
<hr>
数组内容:
<div v-for="(item,index) in arr" :key="index">
{{item}}
</div>
数组长度:
<div>{{count}}</div>
<button @click="addarrbtn">addarrbtn</button>
</div>
</template>
<script setup>
import {ref} from 'vue'
//引入store/index.js定义的实例
import {useStore} from '../store'
//将实例转为动态
import { storeToRefs } from 'pinia';
//储存实例
let store = useStore()
//将实例转为动态对象并结构出来,只能结构state和getters中的内容,不需要结构actions中的方法
let {name,num,changeNum,arr,count} = storeToRefs(store)
console.log(name,num)
const btn = ()=>{
//直接修改state中的值
name.value='李四'
}
const addbtn = ()=>{
//调用actions中的方法,修改state中的值
store.upNum(2)
}
const addarrbtn = ()=>{
var obj = {
name:'aaa',
age:18
}
store.addarr(obj)
}
// const msg = ref('aaa')
// 监听数据变化
watch(() => store.chooseitem, (newValue, oldValue) => {
console.log(newValue)
console.log(oldValue)
store.setchooseitem(newValue,oldValue)
});
// 监听pinia中触发action方法
store.$onAction(({ name, store, args }) => {
console.log(`Action ${name} called on store ${store.$id} with args:`, args)
})
</script>
<style scoped >
</style>