pinia配置流程
1. 安装
yarn add pinia
2. 创建 store/index.js 在 src 文件下
3. 通过 import 导入 createPinia 函数
import { createPinia } from 'pinia'
4.调用 createPinia 函数并定义变量 ,最后导出
const pinia = createPinia()
export default pinia
5. main.js 内引入 pinia 并 use 使用
import { createApp } from 'vue'
import App from './App.vue'
import pinia from './stores/index.js'
createApp(App).use(pinia).mount('#app')
6. 创建 store/modules/counter.js 在 src 文件下
7. 通过 import 从 pinia 内 导入 defineStore
import { defineStore } from 'pinia'
8.调用defineStore函数并定义变量名 , 然后export default 导出
const useCounterStore = defineStore ()
export default useCounterStore
9. defineStore插入 参数 名称,名称 是必传的 参数是 string , 然后插入 pinia 三大天王
const useCounterStore = defineStore (‘counter’,{
state:()=>{
name: 'hello World Pinia'
},
getters:{},
actions:{}
})
10. 统一导出 counter.js 文件 在 store/index.js 内
import { createPinia } from 'pinia'
const pinia = createPinia()
export default pinia
/* 统一导出 */
export * from './modules/counter.js'
11. Vue文件使用pinia
注意:
- pinia内没有 mutations 和 modules
- Vue文件内从 pinia/index.js 导入 useCounterStore 并注册
<template>
{{ store.name }}
</template><script setup>
import { useCounterStore } from '@/store/index.js'
const store = useCounterStore()
</script><style lang="scss" scoped></style>
a: 使用 state
state作用: 存储
(1) state内定义变量
const useCounterStore = defineStore (‘counter’,{
state:()=>{
return{
num: '你好世界'
}
},
getters:{},
actions:{}
})
(2) Vue文件内使用
<template>
{{ store.num}}
</template><script setup>
import { useCounterStore } from '@/store/index.js'
const store = useCounterStore()
</script>
b:使用 getters
getters作用: 计算属性
(1) getters内定义
const useCounterStore = defineStore (‘counter’,{
state:()=>{
return{
num: 10
}
},
getters:{
count: state => {
return state.num + 50
}
},
actions:{}
})
(2) vue文件内使用
<template>
{{ store.count}}
</template><script setup>
import { useCounterStore } from '@/store/index.js'
const store = useCounterStore()
</script>
c: 使用 actions
actions作用: 修改存储数据 包括同步和异步
注意: actions内 是通过 this 去访问 state 内数据
(1) 在actions内定义
const useCounterStore = defineStore (‘counter’,{
state:()=>{
return{
num: 10
}
},
getters:{
count: state => {
return state.num + 50
}
},
actions:{
amend(){
this.num = '我被修改了'
}
}
})
(2) Vue文件内使用
<template>
<button @click="update"> 点我使用 actions修改 state内数据 </button>
</template><script setup>
import { useCounterStore } from '@/store/index.js'
const store = useCounterStore()const update = () => {
state.amend()
}
</script>