1、安装pinia(pinia支持vue2和vue3)
PS D:\web\vue3\exe> cnpm i pinia@2.0.14 -S
2、核心概念与基本使用
Store是一个保存状态和业务逻辑的实体,可以自由的读取和写入,并且通过导入setup中使用。
创建过程:
2.1在src目录下创建一个store文件夹,store文件夹下创建一个index.js文件
2.2在index.js文件中创建仓库
//引入pinia
import { defineStore } from "pinia";
//创建一个实例
//第一个arg:仓库id,唯一值
//第二个arg:选项对象
export const useStore = new defineStore('store', {
//state类似于组件的data,用来存储全局状态的
//state必须是函数:这样是为了在服务端渲染的时候避免交叉请求导致的数据状态污染
state() {
return {
name: '翠花',
}
}
})
2.3在main.js中挂载仓库
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
//挂载store
import { createPinia } from 'pinia'
createApp(App)
.use(router)
.use(createPinia()) //挂载仓库
.mount('#app')
2.4使用仓库,操控state
storeToRefs是将state中的数据进行双向绑定,当改变state中的状态,视图也会相应更新
<template>
仓库
<hr>
{{name}}
---
<button @click="fn()">点我</button>
</template>
<script setup>
//引入store钩子
import {useStore} from '@/store/index.js'
//实现仓库数据双向绑定
import {storeToRefs} from 'pinia';
//创建仓库对象
const store=useStore();
let {name}=storeToRefs(store);//解构赋值,数据双向绑定,关联store
function fn(){
name.value='杨明月'
}
</script>
2.5getters的使用
getters的使用有点类似于computed(对已有属性进行加工,返回一个新属性)有缓存功能,getters是可以对state中的数据进行加工,返回一个新的数据。
getters: {
msg(state) {
return state.name + '么么哒'
}
}
<template>
仓库
<hr>
{{name}}
---
{{msg}}
<button @click="fn()">点我</button>
</template>
<script setup>
//引入store钩子
import {useStore} from '@/store/index.js'
//实现仓库数据双向绑定
import {storeToRefs} from 'pinia';
//创建仓库对象
const store=useStore();
let {name,msg}=storeToRefs(store);//解构赋值,数据双向绑定,关联store
function fn(){
name.value='杨明月'
}
</script>
2.6actions的用法
actions: {
buy(payload) {
console.log(this);
//可以包含异步操作
setTimeout(() => {
this.name = payload
}, 1000)
}
}
function asyncf(){//异步调用仓库
// store.$patch('buy','小黄')
store.buy('小黄')
}
3、完整代码
store/index.js
//引入pinia
import { defineStore } from "pinia";
//创建一个实例
//第一个arg:仓库id
export const useStore = new defineStore('store', {
state() {
return {
name: '翠花',
}
},
getters: {
msg(state) {
return state.name + '么么哒'
}
},
actions: {
buy(payload) {
console.log(this);
//可以包含异步操作
setTimeout(() => {
this.name = payload
}, 1000)
}
}
})
3.2demo.vue
<template>
仓库
<hr>
{{name}}
---
{{msg}}
<button @click="fn()">点我</button>
---
<button @click="asyncf()">异步</button>
</template>
<script setup>
//引入store钩子
import {useStore} from '@/store/index.js'
//实现仓库数据双向绑定
import {storeToRefs} from 'pinia';
//创建仓库对象
const store=useStore();
let {name,msg}=storeToRefs(store);//解构赋值,数据双向绑定,关联store
function fn(){
name.value='杨明月'
}
function asyncf(){//异步调用仓库
// store.$patch('buy','小黄')
store.buy('小黄')
}
</script>
<style scoped>
</style>