Pinia
官方文档Pinia
git 地址 github.com/vuejs/pinia
-
安装
npm install pinia
-
引入注册
import { createApp } from 'vue'
import App from './App.vue'
import {createPinia} from 'pinia'
let app = createApp(App)
app.use(createPinia())
app.mount('#app')
-
初始化仓库Store
- 新建一个文件夹Store
- 新建文件[name].ts
- 定义仓库Store
import { defineStore } from 'pinia'
-
我们需要知道存储是使用定义的
defineStore(),并且它需要一个唯一的名称,作为第一个参数传递我这儿名称抽离出去了
新建文件 store-namespace/index.ts
export const enum Names {
Test = 'TEST'
}
store 引入
import { defineStore } from 'pinia'
import { Names } from './store-namespace'
export const useTestStore = defineStore(Names.Test, {
})
这个名称,也称为id,是必要的,Pania 使用它来将商店连接到 devtools。将返回的函数命名为*use...*是可组合项之间的约定,以使其使用习惯。
- 定义值
State 箭头函数 返回一个对象 在对象里面定义值
import { defineStore } from 'pinia'
import { Names } from './store-namespce'
export const useTestStore = defineStore(Names.Test, {
state:() => {
return {
current: 1,
age: 18
}
},
//类似于computed 可以帮我们去修饰我们的值
getters:{
},
//可以操作异步 和 同步提交state
actions:{
}
})
-
使用
-
State 是允许直接修改值的 例如current++
<template>
<div>
<button @click="Add">+</button>
<div>
{{Test.current}}
</div>
</div>
</template>
<script setup lang='ts'>
import {useTestStore} from './store'
const Test = useTestStore()
const Add = () => {
Test.current++
}
</script>
<style></style>
-
批量修改State的值
在他的实例上有$patch方法可以批量修改多个值
<template>
<div>
<button @click="Add">+</button>
<div>
{{Test.current}}
</div>
<div>
{{Test.age}}
</div>
</div>
</template>
<script setup lang='ts'>
import {useTestStore} from './store'
const Test = useTestStore()
const Add = () => {
Test.$patch({
current:200,
age:300
})
}
</script>
<style></style>
-
批量修改函数形式
推荐使用函数形式 可以自定义修改逻辑
<template>
<div>
<button @click="Add">+</button>
<div>
{{Test.current}}
</div>
<div>
{{Test.age}}
</div>
</div>
</template>
<script setup lang='ts'>
import {useTestStore} from './store'
const Test = useTestStore()
const Add = () => {
Test.$patch((state) => {
state.current++;
state.age = 40
})
}
</script>
<style></style>
-
通过原始对象修改整个实例
$state您可以通过将store的属性设置为新对象来替换store的整个状态
缺点就是必须修改整个对象的所有属性,
<template>
<div>
<button @click="Add">+</button>
<div>
{{Test.current}}
</div>
<div>
{{Test.age}}
</div>
</div>
</template>
<script setup lang='ts'>
import {useTestStore} from './store'
const Test = useTestStore()
const Add = () => {
Test.$state = {
current:10,
age:30
}
}
</script>
<style></style>
-
通过actions修改
定义Actions
在actions 中直接使用this就可以指到state里面的值
import { defineStore } from 'pinia'
import { Names } from './store-naspace'
export const useTestStore = defineStore(Names.TEST, {
state:()=>{
return {
current:1,
age:30
}
},
actions:{
setCurrent () {
this.current++
}
}
})
使用方法直接在实例调用
<template>
<div>
<button @click="Add">+</button>
<div>
{{Test.current}}
</div>
<div>
{{Test.age}}
</div>
</div>
</template>
<script setup lang='ts'>
import {useTestStore} from './store'
const Test = useTestStore()
const Add = () => {
Test.setCurrent()
}
</script>
<style></style>