js获取明天日期、Vue3大菠萝 Pinia的使用

直接上代码

const today = new Date(2019, 2, 28)
const finalDate = new Date(today)
finalDate.setDate(today.getDate() + 3)
 
console.log(finalDate) // 31 March 2019
  • 安装

yarn add pinia
# or with npm
npm install pinia
  • 创建第一个store仓库

1、在src目录下创建store目录

2、创建一个 PiniaTest.ts 的文件(文件名可以根据自己需求来)

import {defineStore} from 'pinia'

// 使用 defineStore 定义一个仓库,
// 组件中需要引入仓库,并使用useStorePinia 进行实例化 
// main 是仓库唯一的ID,可以根据自己的需求定义
export const useStorePinia = defineStore('main', {
     // 闭包
    state () {
        return {
            msg: 'hello word',
            count: 10,
            content: '这是通过getters获取Pinia管理的仓库数据'
        }
    },
    // 简写方式
    // state: () => ({
    //    msg: 'hello word',
    //    count: 10
    // }),
    getters:{
        getMsgFn(){
            return this.content
        }
    },
    actions:{
        // actions 里面可以执行同步和异步任务
        // 也可以接收外部传递进来的参数
        // 可以直接修改仓库的值,此处不能使用箭头函数,否则找不到this,打印显示 undefined
        changeMsg (val) {
            console.log('传入进来的值:', val)
            this.msg = '1111'
            this.count == val;
        }
    }
})
  • 引入并使用步骤

  1. 在 main.js 里面引入pinia

  1. 使用 createPinia 进行实例化

  1. 挂载到Vue身上(实际上是将插件进行注册,给放到已经注册的插件数组列表中)

import { createApp } from 'vue'
// 引入inia
import {createPinia} from 'pinia'
import App from './App.vue'

console.log('createPinia:', createPinia);

// 创建实例
const pinia = createPinia();

console.log('pinia:', pinia);

// 使用插件
createApp(App).use(pinia).mount('#app')
  • Pinia在组价中的使用

<template>
    <div style="background: pink;padding: 10px;margin: 10px 0;">
        <div>组件11111111111</div>
        <div>仓库数据:{{count}}---{{getMsgFn}}</div>
        <button @click="changeStoreCountFn">点击</button>
    </div>
</template>

<script setup>
import {defineProps} from 'vue';
import { storeToRefs } from "pinia";

// 引入仓库
import {useStorePinia} from '../Store/PiniaTest'

// 此处 defineStore 与仓库名一样
const store = useStorePinia();


// 此处可以获取getters 和 actions 中的函数,但是不能直接获取仓库中的数据,需要使用storeToRefs强转ref类型
const {changeMsg, getMsgFn} = store;

// 只有强转ref后数据才是响应式的
const {msg, count} = storeToRefs(store);
console.log(11111, store,storeToRefs(store), msg, count)


// 修改仓库count值
const changeStoreCountFn = () => {

    // 方式 1、通过触发仓库 actions 中定义的函数执行
    changeMsg(++count.value)
    console.log(2222,getMsgFn)


    // 方式 2、读取仓库数据进行修改
    // count.value++
    // msg.value = 'aaaaaa'


    // 方式 3、对象形式修改仓库数据
    // store.$patch({
    //     msg: 'change word',
    //     count: ++count.value
    // })


    // 方式 4、函数形式修改仓库数据
    // store.$patch((state) =>{
    //     state.msg = 'change word';
    //     state.count++
    // })
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值