Pinia 支持两种定义 store 的方式:Options API 和 Setup API
# State
Options:
export const useMainStore = defineStore('main', {
state: () => ({
count: 0
}),
actions: {
increment() {
this.count++
}
}
})
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
Setup:
export const useUserStore = defineStore('userStore', () => {
const username = ref('jack')
const sayHi = () => {
alert(`Hi ${username}`)
}
return { username, sayHi }
})
1
2
3
4
5
6
7
2
3
4
5
6
7
# 如何确保响应式
直接使用
store实例: 直接在模板中使用store实例的属性是正确的做法,这样可以确保属性的响应式:<template> <p>{{ store.count }}</p> <!-- 正确的响应式访问 --> </template> <script setup lang="ts"> import { useCounterStore } from '@/stores/counter'; const store = useCounterStore(); // store 是响应式的 </script>1
2
3
4
5
6
7
8
9使用
computed包装属性: 如果你需要在setup函数中处理store的属性,使用computed包装可以确保响应式:import { computed } from 'vue'; import { useCounterStore } from '@/stores/counter'; const store = useCounterStore(); const count = computed(() => store.count); // 使用 computed 保持响应式1
2
3
4
5使用
toRefs保持响应式:toRefs将store的state转换为响应式的引用:import { toRefs } from 'vue'; import { useCounterStore } from '@/stores/counter'; const store = useCounterStore(); const { count } = toRefs(store); // 使用 toRefs 保持响应式1
2
3
4
5使用pinia提供的
storeToRefsimport { storeToRefs } from 'pinia' const counterStore = useCounterStore() const { name } = storeToRefs(counterStore) // ✅ 保持响应性1
2
3
# 方法和store同时需要解构的情况
可以分开解构
const store = useUserStore()
const { setUserConfig } = store
const { userConfig } = storeToRefs(store)
1
2
3
2
3
# pinia-plugin-persistedstate
export const useUserStore = defineStore('user', () => {
const state = reactive({
name: 'pinia',
age: 100
})
return { state }
},
{
persist: true
}
)
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
高级用法:
export const useUserStore = defineStore(
'user',
() => {
const state = reactive({
name: 'pinia',
age: 100
})
const setName = (name: string) => {
state.name = name
}
return { state, setName }
},
{
persist: {
key: 'user', // 存储的key
storage: localStorage, // 存储方式
pick: ['state.name', 'state.age'] // 指定要持久化的字段
}
}
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20