vite2 + Vue3中 使用 pinia
发布时间
阅读量:
阅读量
相比Vuex而言,pinia的使用更为简便。在功能组件方面,Vuex提供了丰富的功能如状态管理(state)、分段操作(mutations)、数据访问(getters)、行为触发(actions)以及模块化构建(modules)等五种主要功能类型。相比之下,在pinia中仅包含状态管理(state)、数据访问(getters)和行为触发(actions)三种核心功能。在实现方式上存在差异。
安装
yarn add pinia
# or with npm
npm install pinia
代码解读
main.js
import { createApp } from 'vue'
import App from './App.vue'
import { createPinia } from 'pinia'
const pinia = createPinia()
createApp(App)
.use(pinia)
.mount('#app')
代码解读
在src下新建store/index.js
由于Vuex中不再提供modules功能,因此新建一个index.js文件实际上已经具备了独立运行的能力,如果有其他模块需要开发的话,即可以在defineStore函数的第一个参数位置指定唯一标识符
import { defineStore } from 'pinia'
/** * 1. 定义并导出容器
* 参数1: 容器的 ID , 必须唯一, 将来 Pinia 会把所有的容器挂载到跟容器
* 参数2: 选项对象
* 返回值: 一个函数, 调用得到容器实例
*/
export const useIndexStore = defineStore('index', {
/** * 类似于组件的data, 用来存储全局状态
* 1. 必须是函数,这样是为了在服务端渲染的时候避免交叉请求导致的数据状态渲染
* 2. 必须是箭头函数, 这是为了更好的 TS 类型推导
*/
state: () => {
return {
count: 100,
quantity: 10
}
},
/** * 类似于组件的computed, 用来封装计算属性, 有缓存的功能
*/
getters: {
// 接受一个可选参数 state 即 当前ID为index的Store实例 也可以用this 拿到 上面的state的状态值
countTotal(state) {
return state.count * state.quantity
}
},
/** * 类似于组件的 methods 封装业务逻辑, 修改state
* 通过 this 拿到上面 state的状态值
*/
actions: {
countChange(val) {
console.log(val,'actions中的参数--->>>>')
this.count++
this.quantity++
// or
// this.$patch({})
// this.$patch(state => {})
}
}
})
代码解读
组件中使用
<template>
count: {{indexStore.count}}
quantity: {{indexStore.quantity}}
countTotal: {{indexStore.countTotal}}
<hr>
count: {{count}}
quantity: {{quantity}}
countTotal: {{countTotal}}
<hr>
<el-button type="primary" @click="indexStoreChange">修改state数据</el-button>
</template>
<script setup>
import { useIndexStore } from '@/store'
import { storeToRefs } from 'pinia'
// state、getters、actions 里面属性或者方法 都是通过 indexStore “点” 出来使用的
const indexStore = useIndexStore()
// 如果想将状态数据结构出来直接使用 必须引入storeToRefs(否则不是响应式) 来自于 pinia(类似于 reactive响应式,结构使用toRefs)
const { count, quantity, countTotal } = storeToRefs(indexStore)
// 修改state中的数据
const indexStoreChange = () => {
// // 方式一: 最简单的方式就是这样
// indexStore.count++
// indexStore.quantity++
// // 方式二:如果修改多个数据,建议使用 $patch 批量更新
// indexStore.$patch({
// count: indexStore.count + 1,
// quantity: indexStore.quantity + 1
// })
// // 方式三(推荐都使用这个就好): 更好的批量更新的方式: $patch 一个函数 这种性能更好
// indexStore.$patch(state => {
// state.count++
// state.quantity++
// })
// 方式四: 逻辑比较多的时候 可以状态到 actions 中 调用 actions中的方法处理
indexStore.countChange()
}
</script>
<style scoped>
</style>
代码解读
全部评论 (0)
还没有任何评论哟~
