pinia的使用笔记

pinia与vuex的区别

1.pinia没有mutations,只有state,getters,actions

2.官方网址:Pinia | The intuitive store for Vue.js

3.1安装:npm install pinia

注入pinia

3.2在main.js中进行引入

import { createPinia } from 'pinia'

const pinia = createPinia()

app.use(pinia)

3.3:根目录新建store/index.js写入:

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {

     state: () =>{

        return {

            counter:0,

        }

     },

    getters:{},

    actions:{}

  })

3.4在组件中调用:(传统的调用)

1.<template>

    <h2>k组件</h2>

    {{ store.num }}

    {{ store.age }}

</template>

<script setup>

 import { useStore } from "../store"

 const store = useStore()

 console.log(store)

</script>

2.解构方式的调用

<template>

    <h2>k组件</h2>

    {{ num }}

    {{ age }}

</template>

<script setup>

 import { useStore } from "../store"

 const store = useStore()

// 解构

let { num , age } = store

 console.log(store)

</script>

3.如果要修改组件里面的值的话:加入:

import { storeToRefs } from 'pinia'

即:

<template>

    <h2>k组件</h2>

    {{ num }}

    {{ age }}

    <button @click="changeName">修改名称</button>

</template>

<script setup>

 import { storeToRefs } from 'pinia'

 import { useStore } from "../store"

 const store = useStore()

// 解构

let { num , age } = storeToRefs(store)

const changeName = () => {

    num.value = 100

//方法里面实现批量更新

 store.$patch(state => {

        state.num++;

        state.age = 456

    })

}

</script>

3.pinia的getters和actions的使用(actions支持同步和异步加载)

import { defineStore } from 'pinia'

export const useStore = defineStore('main', {

     state: () =>{

        return {

            num:0,

            age:18

        }

     },

    getters:{

        changeNum() {

            console.log('getters')

            return this.num + 100;

        }

    },

    actions:{

        upNum(val) {

            this.num += val

        }

    }

  })

在组件中使用:

<template>

<button @click="changeName">修改名称</button>

    <button @click="btn">操作</button>

</template>

<script setup>

 import { storeToRefs } from 'pinia'

 import { useStore } from "../store"

const store = useStore()

let { num , age ,changeNum } = storeToRefs(store)

//通过getters修改数据

const changeName = () => {

    // num.value = 100

    // age.value = 10

    // 批量更新

    store.$patch(state => {

        state.num++;

        state.age = 456

    })

}

//通过actions修改数据

const btn = () => {

    store.upNum(200)

}

</script>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值