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
-
在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; } } })
-
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>
-
效果图