pinia系列教程
Pinia started as an experiment to redesign what a Store for Vue could look like with the Composition API around November 2019. Since then, the initial principles are still the same, but Pinia works for both Vue 2 and Vue 3 and doesn't require you to use the composition API. The API is the same for both except for installation and SSR, and these docs are targeted to Vue 3 with notes about Vue 2 whenever necessary so it can be read by Vue 2 and Vue 3 users!
官网
创建项目
bash
PS D:\项目文件\代码\pinia项目> npm create vite@latest
√ Project name: ... test
√ Select a framework: » vue
√ Select a variant: » vue-ts
Scaffolding project in D:\项目文件\代码\pinia项目\test...
Done. Now run:
cd test
npm install
npm run dev
安装pinia
bash
npm install pinia -s
main.js
/*
* @Author: jpruby
* @Date: 2022-04-07 20:18:48
* @LastEditors: jpruby
* @LastEditTime: 2022-04-07 20:25:42
* @FilePath: \test\src\main.ts
* @Description: 你看就会,一写就废
* hello world is classical
* Copyright (c) 2022, All Rights Reserved.
*/
import { createApp } from "vue"
import App from "./App.vue"
import { createPinia } from "pinia"
createApp(App).use(createPinia()).mount("#app")
定义仓库
src\store\index.ts
/*
* @Author: jpruby
* @Date: 2022-04-07 20:27:25
* @LastEditors: jpruby
* @LastEditTime: 2022-04-07 21:49:35
* @FilePath: \test\src\store\index.ts
* @Description: 你看就会,一写就废
* 定义容器
* Copyright (c) 2022, All Rights Reserved.
*/
import { defineStore } from "pinia"
export const useCounterStore = defineStore("count", {
//创建状态state
state: () => ({
count: 0,
msg: "hello pinia",
arr: [1, 2, 3, 4],
}),
// 计算属性
getters: {
doubleCount(state) {
return state.count * 2
},
//getter内部值传递传递
oneCount(): number {
return this.doubleCount + 1
},
},
// 方法
actions: {
change() {
this.count += 2
this.msg = "zzz"
},
},
})
组件中的使用
示例HelloWorld.vue
<!--
* @Author: jpruby
* @Date: 2022-04-07 20:18:48
* @LastEditors: jpruby
* @LastEditTime: 2022-04-07 21:48:37
* @FilePath: \test\src\components\HelloWorld.vue
* @Description: 你看就会,一写就废
* hello world is classical
* Copyright (c) 2022, All Rights Reserved.
-->
<script setup lang="ts">
import { storeToRefs } from "pinia";
import { toRefs } from "vue";
import { useCounterStore } from "../store";
const store = useCounterStore();
// 解构对象 reactive->toRefs
const { count, msg, arr } = toRefs(store);
function increatment() {
//第一种改变仓库值的方法
// store.count++
// store.msg = "hello jpruby"
//第二种改变仓库值的方法
// store.$patch((state) => {
// (state.count = store.count + 1), (state.msg = "hello jxq"), state.arr.push(6);
// });
//第三种 actions
store.change()
}
</script>
<template>
<h1>{{ msg }}</h1>
<h1>{{ arr }}</h1>
<h1>{{ store.doubleCount }}</h1>
<h1>{{ store.oneCount }}</h1>
<button type="button" @click="increatment">count is: {{ count }}</button>
</template>
<style scoped>
a {
color: #42b983;
}
label {
margin: 0 0.5em;
font-weight: bold;
}
code {
background-color: #eee;
padding: 2px 4px;
border-radius: 4px;
color: #304455;
}
</style>
\