十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
今天小编给大家分享一下Vue3中如何引入Pinia存储库并使用的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

创新互联专注为客户提供全方位的互联网综合服务,包含不限于做网站、网站制作、临河网络推广、重庆小程序开发、临河网络营销、临河企业策划、临河品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;创新互联为所有大学生创业者提供临河建站搭建服务,24小时服务热线:18980820575,官方网址:www.cdcxhl.com
1.用自己最喜欢的方式安装
yarn add pinia # 或者使用 npm npm install pinia
2.main.js引入
import { createApp } from 'vue'
import App from './App.vue'
const app=createApp(App)
import { createPinia } from 'pinia' //引入pinia
app.use(createPinia())
app.mount('#app')3.创建store文件并配置内部的index.js文件
import { defineStore } from 'pinia' //引入pinia
//这里官网是单独导出 是可以写成默认导出的 官方的解释为大家一起约定仓库用use打头的单词 固定统一小仓库的名字不易混乱
export const useCar=defineStore("test",{
state: () =>{
return ({
msg:"这是pinia",
name:"小小",
age:18
}) //为了避免出错,返回的值用()包起来
}
})4.组件使用方法
{{store.msg}}{{store.name}}{{store.age}}
5.重置store.$reset()
{{store.msg}}{{store.name}}{{store.age}}
6.群体修改store.$patch,可以将pinia的数据进行同一修改
特点:批量修改但状态只刷新一次
{{store.msg}}{{store.name}}{{store.age}}
7.订阅修改
//可以通过 store 的 $subscribe() 方法查看状态及其变化,通过patch修改状态时就会触发一次
store.$subscribe((mutation, state) => {
// 每当它发生变化时,将整个状态持久化到本地存储
localStorage.setItem('hello', JSON.stringify(state))
})8.Getter
Getter 完全等同于 Store 状态的 计算值。 它们可以用 defineStore() 中的 getters 属性定义。 他们接收“状态”作为第一个参数以鼓励箭头函数的使用:(ps:虽然鼓励但是依然提供了非es6玩家的使用方式 内部可以用this代表state)
//store/index.js文件
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
getters: {
doubleCount: (state) => state.counter * 2,
},
})
//组件中直接使用: Double count is {{ store.doubleCount }}
9.Actions
在pinia中没有提供mutaion 因为Actions就够了(它可以异步同步的统一修改状态)之所以提供这个功能 就是为了项目中的公共修改状态的业务统一
export const useStore = defineStore('main', {
state: () => ({
counter: 0,
}),
actions: {
increment() {
this.counter++//1.有this
},
randomizeCounter(state) {//2.有参数 想用哪个用哪个
state.counter = Math.round(100 * Math.random())
},
randomizeCounter(state) {
//异步函数.接口成功赋值
ajax.hplBaseApi("app/productSelection/categoryRows", {}, "post").then((res) => {
state.counter = res.data.length
});
}
},
})
//组件中的使用:
setup() {
const store = useStore()
store.increment()
store.randomizeCounter()
}以上就是“Vue3中如何引入Pinia存储库并使用”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注创新互联行业资讯频道。