vue3.0 --->Pinia 使用方式

Pinia
Pinia是一个全新的Vue状态管理库,支持vue2.0以及vue3.0(不会受版本印象),支持TypeScript,
在这里插入图片描述

vueX,Vuex3(对应Vue2.x) & Vuex4(对应Vue3.x)。

Pinia地址

官网地址
测试功能地址
创建项目

yarn create @vitejs/app vue3_ts_vite_pinia

Pinia初始化以及使用

安装Pinia

npm i pinia

挂载Pinia

import { createApp } from 'vue';
import App from './App.vue';
import { createPinia } from 'pinia';

//状态管理
const pinia = createPinia();
const app = createApp(App);

app.use(pinia)
app.mount('#app')

创建Store

import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
  state: () => {
    return { 
    	count: 0,
    	coolBoy: ['靓女', '靓坤']
   	}
  },
  getters: {
  	findCoolBoy(state) {
      // autocompletion! ✨
      double: ((state) => state.coolBoy
    },
  },
  actions: {
    increment() {
      this.count++
    },
  },
})

调用

import { useCounterStore } from '@/stores'

export default {
  setup() {
    const counter = useCounterStore()
    counter.count++
    // with autocompletion ✨
    counter.$patch({ count: counter.count + 1 })
    // or using an action instead
    counter.increment()
  },
}
//或者
<script setup lang="ts">
import { useCounterStore } from '@/store';

const store = useCounterStore();
const counts = store;
const store.$patch({ count: counter.count + 1 })
store.increment()
const msg = ref('Hello');
</script>

解构

main.ts
import { useCounterStore } from '@/store';
import { storeToRefs } from 'pinia'
const { count } = storeToRefs(store);
const store = useCounterStore();

//template模板
<template>
<p>Count is {{ store.count }} now</p>
<p>结构数量信息:::{{ count }}</p>
</template>

Getters调用

main.ts
state: () => ({
    name: '超级管理员',
    count: 0,
}),
getters: {
  getCountBuff(state) {
    console.log('getters调用同');
    return `${state.name}****${state.name}`
  },
  getMsgWithThis(): string {
    console.log('gettersThis调用同');
    return `${this.name}****${this.name}`
  }  
},
    
index.vue
<h2>Pinia中的Getters</h2>
<p>{{ store.getCountBuff }}</p>
<p>{{ store.getCountBuff }}</p>
<h2>Pinia中的Getters this指向问题</h2>
<p>{{ store.getMsgWithThis }}</p>
<p>{{ store.getMsgWithThis }}</p>

Getters相互调用

store.ts
/**
 * 相互调用案例信息
 */
import { defineStore } from 'pinia'

export const allanStore = defineStore({
  id: 'store',
  state: () => ({
    moveList: ['泰坦尼克号', '肖申克的救赎', '阿甘当兵日记', '星际穿越']
  }),
  getters: {
  },
  actions: {
  },
})

main.ts
import { allanStore } from './store'

getAllanStore(): string[] {
   return allanStore().moveList
}

index.vue
<h2>Pinia中的Getters 相互调用</h2>
<ul>
  <li v-for="(item, index) in store.getAllanStore" :key="index">{{ item }}</li>
</ul>

gitee地址

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值