选项式:
1.定义Store
import { defineStore } from 'pinia'
// option api 选项式
export const useAlterStore = defineStore('alter', {
state: () => {
return {
num: 1
}
},
getters: { // 可以看做是计算属性
doubleCount: (state) => state.num * 2
},
actions: {
// 同步方法
add() {
this.num++
},
// 异步方法
async asyncAdd() {
await new Promise((resolve) => {
setTimeout(resolve, 1000)
})
this.add()
}
}
})
- 使用Store
//引入store
import { useAlterStore } from '../store/useAlterStore.js';
import { storeToRefs } from 'pinia'
const store = useAlterStore(); // 拿到仓库
const { num, doubleCount } = storeToRefs(store); // 把仓库中的数据变成响应式
const { add, asyncAdd } = store // 拿到仓库方法
组合式:
1.定义Store
import { defineStore } from 'pinia'
import { reactive, computed } from 'vue'
export const useListStore = defineStore('list', () => {
const list = reactive({
inputValue: '1',
conter: 100,
items: [
{
txt: '学习pinia',
isCompleted: true
}
]
})
const doubleCounter = computed(() => list.conter * 2)
const deleteItem = (index) => {
list.items.splice(index, 1)
}
return {
list,
doubleCounter,
deleteItem
}
})
- 使用Store
//引入store
import { useAlterStore } from '../store/useAlterStore.js';
import { storeToRefs } from 'pinia'
// 获取仓库
const store = useListStore()
const { list, doubleCounter } = storeToRefs(store) // 把仓库中的数据变成响应式
const { deleteItem } = store // 拿到仓库方法
重置state
const store = useStore()
store.$reset()
注意:pinia使用setup函数创建store $reset()失效
可以使用options创建或者重写一个$reset方法
变更state
store.$patch({
num: inputVal.value
})
全局挂载
main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
import './index.css'
const pinia = createPinia()
createApp(App).use(pinia).mount('#app')