一、安装 pinia
yarn add pinia
# 或者使用 npm
npm install pinia
二、在vue3中使用
1、创建一个 pinia(根存储)并将其传递给应用程序
store.js
import { createPinia } from 'pinia';
const store = createPinia();
export default store;
main.js
import { createApp } from 'vue'
import App from './App.vue'
import store from "@/store/store.js"
const app = createApp(App)
app.use(store).mount('#app')
todoStrore.js
import { defineStore } from 'pinia'
export const todos = defineStore('todos', {
state: () => ({
/** @type {{ text: string, id: number, isFinished: boolean }[]} */
todos: [],
/** @type {'all' | 'finished' | 'unfinished'} */
filter: 'all',
// type 会自动推断为 number
nextId: 0,
}),
getters: {
finishedTodos(state) {
// 自动完成! ✨
return state.todos.filter((todo) => todo.isFinished)
},
unfinishedTodos(state) {
return state.todos.filter((todo) => !todo.isFinished)
},
/**
* @returns {{ text: string, id: number, isFinished: boolean }[]}
*/
filteredTodos(state) {
if (this.filter === 'finished') {
// 自动调用其他 getter ✨
return this.finishedTodos
} else if (this.filter === 'unfinished') {
return this.unfinishedTodos
}
return this.todos
},
},
actions: {
// 任何数量的参数,返回一个 Promise 或者不返回
addTodo(text) {
// 你可以直接改变状态
this.todos.push({ text, id: this.nextId++, isFinished: false })
},
},
})
在组件中使用
为了从 Store 中提取属性同时保持其响应式,您需要使用storeToRefs()
。 它将为任何响应式属性创建 refs。
在vue3的setup中,ref接受一个内部值,返回一个响应式的、可更改的 ref 对象,此对象只有一个指向其内部值的属性 .value
。
<template>
<div class="container">
// code
</div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { Toast } from 'vant'
import { storeToRefs } from "pinia";
import { todoStore } from "@/store/todoStore";
// state
const { todos, filter, nextId } = storeToRefs(chatStore);
// actions
const { finishedTodos, unfinishedTodos } = chatStore;
const show = ref(false)
const playStatus = ref(false)
const customFieldName = ref({
text: 'text',
value: 'value',
})
let nowMusicIndex = 0;
const musicList = []
const audioObj = new Audio(musicList[0])
audioObj.autoplay = true;
audioObj.loop = true;
let vanPickerObj = null
audioObj.onerror = () => {
Toast('音频资源加载出错了~')
}
onMounted(() => {
})
onUnmounted(() => {
clearInterval(playIntervalId.value)
})
// 设置时间选择组件对象
const setVanPicker = (el) => {
vanPickerObj = el;
}
const showActionSheet = () => {
show.value = true
}
const stopMusic = () => {
playStatus.value = false
}
const handleBackClick = () => {
router.replace("/home");
};
</script>
<style lang="less" scoped>
// code
</style>