安装
yarn add pinia
或者使用 npm
npm install pinia
pinia的基本使用
state
大多数时候,state 是 store 的核心部分。 我们通常从定义应用程序的状态开始。 在 Pinia 中,状态被定义为返回初始状态的函数。 Pinia 在服务器端和客户端都可以工作。
import { createApp } from "vue";
import "./style.css";
import App from "./App.vue";
import { createPinia } from "pinia";
const app = createApp(App);
app.use(createPinia());
app.mount("#app");
创建一个store文件
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counterStore", {
state: () => {
return {
counter: 0,
};
},
});
测试pinia
<template>
<div></div>
</template>
<script setup>
import { useCounterStore } from "../store/counterStore";
const counterStore = useCounterStore();
console.log(counterStore);
</script>
打印结果如下:
action
Actions 相当于组件中的 methods。 它们可以使用 defineStore() 中的 actions 属性定义,并且它们非常适合定义业务逻辑:
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counterStore", {
state: () => {
return {
counter: 0,
};
},
actions: {
increment(val) {
console.log(val);
this.counter++;
},
},
});
<template>
<div>
<!-- {{ counterStore.counter }} -->
{{ counter }}
<button @click="add()">点击增加</button>
</div>
</template>
<script setup>
import { useCounterStore } from "../store/counterStore";
import { storeToRefs } from "pinia";
// 方式一
// const counterStore = useCounterStore();
// const add = () => {
// counterStore.increment("增加counter");
// };
// 方式二
const counterStore = useCounterStore();
// 让counter变得响应式
const { counter } = storeToRefs(counterStore);
const increment = counterStore.increment;
const add = () => {
counterStore.increment("增加counter");
};
</script>
效果如图:
优化一下路径
打开vite.config.js配置文件
使用相对路径时太多"…/…/",看起来不美观
import { useCounterStore } from “…/store/counterStore”;
变为
import { useCounterStore } from “@/store/counterStore”;
import { defineConfig } from "vite";
import vue from "@vitejs/plugin-vue";
import path from "path";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
},
},
});
json-server模拟数据
npm install json-server -g
启动json-server
json-server .\vite-project\src\data\api.json -p 9000
启动成功
安装axios
npm i axios -S
import { defineStore } from "pinia";
import axios from "axios";
export const useCounterStore = defineStore("counterStore", {
state: () => {
return {
products: [],
};
},
actions: {
async loadData() {
let result = await axios.get("http://localhost:9000/data");
console.log("result:", result);
this.products = result.data;
},
},
});
<template>
<div>
<ul>
<li v-for="item in products">
{{ item.name }}
</li>
</ul>
<button @click="add()">点击请求数据</button>
</div>
</template>
<script setup>
import { useCounterStore } from "@/store/counterStore";
import { storeToRefs } from "pinia";
const counterStore = useCounterStore();
const { products } = storeToRefs(counterStore);
const loadData = counterStore.loadData;
const add = () => {
loadData();
};
</script>