vue3引入pinna配置使用

3 篇文章 0 订阅

引入pinna

npm install pinia -S

在src文件里面创建store文件-index.ts 在main.ts中引用pinna

import {createPinia} from 'pinia'
const store = createPinia()
createApp(App).use(router).use(store).mount('#app')

index.ts

index.ts文件

defineStore定义容器
参数1:是对仓库的命名,名称必须具备唯一性;
参数2:配置的选项对象,即state、getters、actions,
其中state的写法必须是函数,为了避免在服务端交叉请求导致的状态数据污染,
而且必须是箭头函数,为了更好的TS类型推导。
import { defineStore } from 'pinia'// 引入

export const useStore = defineStore("main", {
   state: () => {
      return {
         count: 10,
         name: 'wl',
         arr: [1, 2, 3],
      }
   },
   //类似于computed 可以帮我们去修饰我们的值
   getters: {
      //  函数接受一个可选参数 state
      count10(state) { return state.count + 10 }
   },
   //可以操作异步 和 同步提交state
   actions: {
      //不要使用箭头函数定义action,因为箭头函数绑定外部this
      changeState(num: any, str: any) {   //不要使用箭头函数定义action,因为箭头函数绑定外部this
         this.count += num
         this.name += str
         this.arr.push(5)
      }
      // this.$patch({})或this.$patch(state=>{})    //还可通过$patch修改state的数据
   }
})


其它页使用

其他页面使用

<template>
  <div>
    <span>数量:{{ test.count }}---{{ count }}</span>
    <br>
    <span>姓名:{{ test.name }}---{{ name }}</span>
    <br>
    <span>arr:{{ test.arr }}---{{ arr }}</span>
  </div>
</template>
<script setup lang="ts">
import { useStore } from "./store/index"//引入store文件
import { storeToRefs } from 'pinia'//引入storeToRefs
import { toRefs } from "vue";
const test = useStore()//声明赋值引入的store文件
const { count, name, arr, count10 } = storeToRefs(test)//数据解构出来
//使用storeToRefs函数将state里的数据解构出来实现响应式

// 3种方法 一种通过test.自定义名称进行调用
// 另一种是修改多个数据,用$patch 
// 另一种是直接通过state
// test.$patch({
//   count: test.count,
//   name: test.name,
//   arr: [...test.arr, 4]
// })

//  test.$patch(state => {
//  state.count++
//  state.name += '~~'
//  state.arr.push(5)
//})

test.changeState(10,'hello') //逻辑比较多用action
</script>

<style scoped></style>

参考

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值