1、vue3中storeToRefs的使用,channel.js:
import {defineStore } from 'pinia' import {ref} from 'vue' import axios from 'axios' export const useChannelStore = defineStore('channel', () => { const channelList = ref([]) //声明操作数据的方法 const getList = async () =>{ const {data:{data}} = await axios.get('URL') channelList.value = data.channels } return { channelList,getList } })
App.vue:
<script setup> import {useChannelStore} from '@/stores/channel.js' import { storeToRefs } from 'pinia'; const channelStore = useChannelStore() const {channelList} = storeToRefs(channelStore) //方法不需要响应式 const {getList} = channelStore </script> <template> <div> <button @click="getList">获取列表</button> <li v-for="item in channelList" :key="item.id">{{ item }}</li> </div> </template>
2、Pinia持久化
1)安装插件:
npm i pinia-plugin-persistedstate
2)main.js 使用
import persist from 'pinia-plugin-persistedstate' ... app.use(createPinia().use(persist))
3) 在store仓库中使用,persist : true开启