vue的更新相当之快,我们的学习脚步也要紧跟上!vue里面的中重难点是状态管理,官方的vuex已经更新到vuex5.0了,很多替代vuex的轻量级框架也层出不穷!比如今天我要介绍的piniajs,去掉了mutation操作state里面数据的方法,数据的操作更简便,没有了vuex的繁琐
piniajs官方文档链接
该库的详细文档大家可以去官网研究!下面我来学习利用该框架实现vue的todolist应用
最终的实现效果
###vite搭建v3项目
安装piniajs
yarn add pinia
# or with npm
npm install pinia
全局注册pianiajs
import { createApp } from "vue";
import App from "./App.vue";
import "./index.css";
import { createPinia } from "pinia";
const app = createApp(App);
app.use(createPinia());
app.mount("#app");
store
//users.js
// @ts-check
import { defineStore, acceptHMRUpdate } from "pinia";
export const useUserStore = defineStore({
id: "user", //每个store文件必须有个唯一的标志
state: () => ({
name: "Pianiajs",
}),
actions: {
add() {
this.$patch({
count: ++this.count,
});
},
},
});
// @ts-ignore,热更新的配置
if (import.meta.hot) {
// @ts-ignore
import.meta.hot.accept(acceptHMRUpdate(useUserStore, import.meta.hot));
}
import { defineStore, acceptHMRUpdate } from "pinia";
import { useUserStore } from "./users";
export const useCartStore = defineStore({
id: "cart",
state: () => ({
lists: [],
}),
getters: {
items: (state) => {
return state.lists.reduce((items, item) => {
const hasItem = items.find((it) => it.name == item);
if (!hasItem) {
items.push({
name: item,
amount: 1,
});
} else {
hasItem.amount++;
}
return items;
}, []);
},
},
actions: {
addItem(name) {
this.lists.push(name);
console.log(this.lists, "pppp");
},
removeItem(name) {
const index = this.lists.lastIndexOf(name);
if (index > -1) this.lists.splice(index, 1);
},
},
});
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useCartStore, import.meta.hot));
}
App.vue
<template>
<h2>Hello {{ user.name }}</h2>
<p>{{ user.count }}</p>
<form @submit.prevent="addItemToCart" data-testid="add-items">
<input type="text" v-model="itemName" />
<button>Add</button>
</form>
<form action="">
<ul>
<li v-for="(e, index) in cart.items" :key="index">
{{ e.name }}({{ e.amount }})
<button
style="margin-left: 77px"
@click="cart.removeItem(e.name)"
type="button"
>
X
</button>
</li>
</ul>
<button
:disabled="!cart.items.length"
@click="clearCart"
type="button"
data-testid="clear"
>
Clear the cart
</button>
</form>
</template>
import { defineComponent, ref } from "vue";
import { useUserStore } from "./store/users";
import { useCartStore } from "./store/cart";
export default defineComponent({
setup(props) {
const username = ref("zhangsan"); //初始值
const user = useUserStore(); // 获取store中的值
const cart = useCartStore(); // 获取store中的值
const itemName = ref("");
const addItemToCart = () => {
if (!itemName.value) {
return alert("内容不能为空");
}
cart.addItem(itemName.value); // 执行store中的方法,改变state里面的值
itemName.value = "";
};
const clearCart = () => {
if (window.confirm("Are you sure you want to clear the cart?")) {
cart.lists = []; // 执行store中的方法,改变state里面的值
}
};
return {
user,
itemName,
addItemToCart,
cart,
clearCart,
};
},
});
这样一个pinia实例就完成了!可以直接改state里面的值,而vuex则是必须通过mutation方法去操作state,相对vuex,piniajs更符合我们的常规开发思维!