vue3替代vuex的框架piniajs实例教程

2 篇文章 0 订阅
1 篇文章 0 订阅

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更符合我们的常规开发思维!

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值