vue3中Pinia初识与安装

Pinia初识与安装

1、开发插件安装
1、禁用Vetur
2、安装Vue Language Features (Volar)
3、安装Element UI Snippets
2、pinia官网

https://pinia.vuejs.org/

https://pinia.vuejs.org/introduction.html

3、pinia安装

3.1、安装依赖

npm install pinia

3.2、main.ts引入pinia

//引入Pinia构造函数
import { createPinia } from 'pinia'
// 实例化 Pinia
const pinia = createPinia()
const app = createApp(App);
app.use(ElementPlus).use(router).use(pinia).mount('#app')

4、使用pinia

4.1、src下新建store

然后store下新建test目录,并建index.ts文件

import { defineStore } from 'pinia'
//定义store
export const testStore = defineStore('testStore', {
    state: () => {
        return {
            count: 0
        }
    },
    getters: {
        getCount(state) {
            return state.count
        }
    },
    actions: {
        setCount(count: number) {
            console.log(count)
            this.count = count;
        }
    }
})

4.2、HelloWorld.vue页面

<template>
  <h1>{{ store.count }}</h1>
  <h1>{{ count }}</h1>
  <el-button type="primary" size="default" @click="addBtn">新增</el-button>
  <el-icon>
    <search />
  </el-icon>
</template>
<script setup lang="ts">
import { computed } from "vue";
import { testStore } from "@/store/test/index";
import { storeToRefs } from "pinia";
// 获取store
const store = testStore();
//这种方式,数据会失去响应性
// const {count}=store
// 解决响应性丢失的问题
// const { count, msg } = storeToRefs(store);

const count = computed(() => {
  return store.getCount;
});
const addBtn = () => {
  //第一种改变数据的方式
  // store.count++;
  //第二种改变数据的方式
  // store.setCount(++store.count);
  //第三种改变数据的方式
  // store.$patch({
  //   count: ++store.count,
  // });
  //第四种改变数据的方式
  store.$patch((state)=>{
    state.count = ++state.count 
  })
};
</script>

<style scoped></style>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值