Vue3+Vite+Pinia+Naive后台管理系统搭建之五:Pinia 状态管理

前言

如果对 vue3 的语法不熟悉的,可以移步Vue3.0 基础入门,快速入门。

Pinia 详情可移步官网参看:Pinia 官网

github 开源库:Vue3-Vite-Pinia-Naive-Js

gitee   开源库:Vue3-Vite-Pinia-Naive-Js

1. 安装依赖

yarn add pinia
// or
npm install pinia

2. 新增 src/store/user.js 用户信息、token状态管理

import { defineStore } from "pinia";

export const useUserStore = defineStore({
  id: "userStore",
  state: () => {
    return {
      token: "888888",
      user: {
        name: "yqcoder",
        age: 18,
      },
    };
  },
  getters: {
    ageAfter(state) {
      return state.user.age + 10;
    },
  },
  actions: {
    // 登录接口
    async login() {
      return new Promise((resolve, reject) => {});
    },
    // 退出接口
    async logout() {
      return new Promise((resolve, reject) => {});
    },
    // 获取用户信息
    async getInfo() {
      return new Promise((resolve, reject) => {});
    },
  },
});

3. 编辑 src/main.js 引入store 状态

import { createApp } from "vue";
import App from "./App.vue";

// 共用样式
import "@/assets/style/index.scss";
// 路由
import router from "@/router/index.js";
// store 状态管理
import { createPinia } from "pinia";

createApp(App).use(createPinia()).use(router).mount("#app");

4. 编辑 src/pages/home.vue 引入 store 状态

<script setup>
import { computed } from "vue";
import { NButton, useDialog } from "naive-ui";
import router from "@/router/index.js";
import { useUserStore } from "@/store/user.js";

let userStore = useUserStore();

let user = computed(() => {
  return userStore.user;
})

let ageAfter = computed(() => {
  return userStore.ageAfter;
})

let toPage = (name) => {
  router.push({ name });
};

let handleShowMsg = () => {
  window.$msg.success("success message");
};

const dialog = useDialog();
let handleShowDialog = () => {
  dialog.warning({
    title: "警告",
    content: "你确定?",
    positiveText: "确定",
    negativeText: "不确定",
    onPositiveClick: () => {
      window.$msg.success("确定");
    },
    onNegativeClick: () => {
      window.$msg.error("不确定");
    },
  });
};
</script>

<template>
  <div class="home">
    home
    <n-button @click="toPage('demo')" type="primary">goDemo</n-button>
    <n-button @click="toPage('login')" type="warning">goLogin</n-button>
    <n-button @click="handleShowMsg" type="info">show message</n-button>
    <n-button @click="handleShowDialog" type="error">show dialog</n-button>
    <div class="user__info">
      <p class="name">姓名: {{ user.name }}</p>
      <p class="age">年龄: {{ ageAfter }}</p>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>

综上

Pinia 安装完成。下一章:Vue3+Vite+Pinia+Naive后台管理系统搭建之六:Axios 网络请求

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yqcoder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值