14.pinia初始与安装

pinia初始与安装


pinia官网


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

在这里插入图片描述

在这里插入图片描述

pinia安装


npm install pinia
在这里插入图片描述

main.ts引入pinia

import { createApp } from 'vue'
// import './style.css'
import App from './App.vue'
import router from './router/index'
// 引入element plus
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'

//引入pinia构造函数
import { createPinia } from 'pinia'

// 实例化pinia
const pinia = createPinia()

const app = createApp(App);
app.use(router).use(ElementPlus).use(pinia).mount('#app')
// createApp(App).mount('#app')
for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
  }

使用pinia


  1. 在src下新建store
    然后store下新建test目录与menu,并建index.ts文件
    在这里插入图片描述

     import { defineStore } from "pinia";
     // 创建store
     // defineStore第一个参数:唯一的,不可重复
     export const testStore = defineStore('testStore',{
         state:()=>{
             return{
                 count: 0
             }
         },
         // 获取值
         getters:{
             getCount(state){
                 return state.count
                 // 获取count的值
             }
         },
         // 改变state的值
         actions:{
             setCount(count:number){
                 this.count = count;
             }
         }
     })
    
  2. HelloWorld.vue

    
     <template>
       <h1>{{ count }}</h1>
       <div>111111</div>
       <el-button>Default</el-button>
       <el-button icon="Edit" type="primary">编辑</el-button>
       <el-button @click="addBtn" icon="Plus" type="success">新增</el-button>
       <el-button type="info">Info</el-button>
       <el-button type="warning">Warning</el-button>
       <el-button type="danger">Danger</el-button>
       <el-icon>
         <Edit />
       </el-icon>
     </template>
     
     <script setup lang="ts">
     import { computed } from 'vue'
     import { testStore } from '@/store/test/index';
     
     // 获取store
     const  store = testStore()
     // 从store里面获取count
     const count = computed(()=>{
       return store.getCount
     })
     
     // 改变store里面的值
     const addBtn = ()=>{
       store.setCount(++store.count)
     }
     </script>
     
     <style scoped>
     .read-the-docs {
       color: #888;
     }
     </style>
    
  3. 效果图
    在这里插入图片描述

  • 29
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值