零基础、大白话,Vue3全篇通俗疗法(中):通信、UI、路由、状态【用得上】

发布于:2025-06-23 ⋅ 阅读:(13) ⋅ 点赞:(0)

上篇链接:零基础、大白话,Vue3全篇通俗疗法(上)

        前文主要讲了VUE的基础知识,最终目的是为了实现看得懂VUE代码,但掌握那些不足以应对日常工作,接下来我们将补齐相应周边技术,这篇的目的是让大家用得了。

通信-Axios

        为什么要用Axio

        Vue只是一个前端框架,不具备与后端交互的能力,引用Axios就具备了前后端通信的能力了。

安装

 npm install axios

全局引

main.ts

import './assets/main.css'
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.mount('#app')

创建模拟的请求数据文件 public/data.json

{
  "compilerOptions": {
    "target": "es2016",
    "module": "commonjs",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true
  }
}

模拟请求处理

<script setup lang="ts">
import axios from "axios";
import {ref} from "vue";

const compilerOptions = ref({
    target: "",
    module: "",
    esModuleInterop: true,
    forceConsistentCasingInFileNames: true,
    strict: true,
    skipLibCheck: true
});

async function changeMsg() {
  const res = await axios.get('/data.json');
  if (res.data && res.data.compilerOptions) {
    if (res.data.compilerOptions.target !== undefined) {
      compilerOptions.value.target = res.data.compilerOptions.target;
      compilerOptions.value.module = res.data.compilerOptions.module;
    } else {
      console.error('compilerOptions 中缺少 target 字段:', res.data.compilerOptions);
    }
  } else {
    console.error('数据结构不完整,缺少 compilerOptions 或 data 为空:', res.data);
  }
}
</script>

<template>
  <div>
    <h1>{{ compilerOptions.target }}</h1>
    <h1>{{ compilerOptions.module }}</h1>
    <button @click="changeMsg">获取数据</button>
  </div>
</template>

ElementUI

为什么需要

VUE只是一个前端框架,作为前端是直接展示给用户的,那么就需要让它赏心悦目。那么ElementUI是一个不错的选择,当然也有很多类似的UI,大同小异。

安装

npm install element-plus --save

配置

配置全局启用 main.ts

import './assets/main.css'
import 'element-plus/dist/index.css' //1.启用全局css
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import ElementPlus from 'element-plus'  //2.引用
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.use(ElementPlus) //3.启用element-plus
app.mount('#app')

使用

<template>
  <div>
    <el-button type="primary">获取数据</el-button>
    <el-button type="success">Success</el-button>
  </div>
</template>

路由

为什么要用路由

在MVC框架下的系统通过Controller层实现路由跳转,但现在的注流是MVVM模式,前后端分离,所以页面的跳转需要前端自己根据自己业务的需求自行路由。

安装

npm install vue-router@4

配置

1.配置router.ts

routes对象数组说明

path:路由指向

name:路由标识(不能重复)

component:组件(一般定义动态组件)

children:嵌套另一个routes对象数组,实现子级路由

import { createRouter, createWebHistory } from 'vue-router'

// 创建路由实例
const router = createRouter({
  // 使用 Web History 模式
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      // 首页路由
      path: '/',
      name: 'home',
      component: () => import('@/com/head.vue')
    },
    {
      // Boot 页面路由
      path: '/com/boot',
      name: 'Boot',
      component: () => import('@/com/boot.vue'),
      children: [
        {
          // 左腿页面路由
          path: 'leftLeg',
          name: 'LeftLeg',
          component: () => import('@/com/leftLeg.vue')
        },
        {
          // 右腿页面路由
          path: 'rightLeg',
          name: 'RightLeg',
          component: () => import('@/com/rightLeg.vue')
        }
      ]
    }
  ]
})

// 导出路由实例
export default router

2.全局启用 main.ts

import './assets/main.css'
import 'element-plus/dist/index.css'
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import ElementPlus from 'element-plus'
import Router from './router/router.ts'
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.use(ElementPlus)
 app.use(Router) // 启用Vue Router
app.mount('#app')

使用

1.用<router-view>标签启用路由器

2.用<RouterLink to="路径">指向路由

<script setup lang="ts">
</script>

<template>
  <div>
    <h1>Hello World</h1>
    <!-- 导航栏 -->
    <nav>
      <RouterLink to="/">测试一下</RouterLink>
      <RouterLink to="/com/boot">测试一下222</RouterLink>
    </nav>
    <!-- 路由视图 -->
    <router-view />
  </div>
</template>

状态管理

为什么用状态管理

我们组件在大多数情况下需要数据共享,虽然通过组件互传与能实现数据同步(状态同步),但是项目稍大维护起来将变成灾难。

安装

 npm i pinia

配置

main.ts

import './assets/main.css'
import 'element-plus/dist/index.css'
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import ElementPlus from 'element-plus'
import Router from './router/router.ts'
import { createPinia } from 'pinia'
const pinia = createPinia()
const app = createApp(App)
app.config.globalProperties.$axios = axios
app.use(ElementPlus)
app.use(Router)
app.use(pinia)
app.mount('#app')

使用

创建store文件:userStore.ts

import {defineStore} from "pinia";

/**
 * 用户存储模块
 * 包含用户的基本信息和相关操作
 */
export const useUserStore = defineStore('user', {
  /**
   * 存储的状态
   * @returns 用户状态对象
   */
  state: () => ({
    name: '张三', // 用户名
    age: 18       // 用户年龄
  }),
  /**
   * 获取器
   */
  getters: {
    /**
     * 获取用户的年龄
     * @param state 当前状态
     * @returns 用户的年龄
     */
    getAge: (state) => state.age
  },
  /**
   * 动作(用于修改状态)
   */
  actions: {
    /**
     * 设置用户的年龄
     * @param age 新的年龄值
     */
    setAge(age: number) {
      this.age = age;
    }
  }
});

使用

<script setup lang="ts">
// 引入用户状态管理模块
import { useUserStore } from '@/store/userStore'

// 获取用户状态实例
const userStore = useUserStore()

// 定义修改年龄的方法
function change(){
  // 调用状态中的setAge方法,将年龄加1
  userStore.setAge(userStore.age+1)
}
</script>

<template>
  <div>
    <!-- 显示用户名称 -->
    <h1>{{  userStore.name  }}</h1>
    <!-- 显示用户年龄 -->
    <h1>{{  userStore.age  }}</h1>
    <!-- 按钮用于触发年龄修改 -->
    <el-button type="primary" @click="change">修改</el-button>
  </div>
</template>

持久化

本身Pinia 并不支持持久化,换言之F5刷新就会让数据还原;如何解决这个问题呢,pinia-plugin-persist插件可以解决这个问题。(这个插件支持Pinia2.0+,但官方不支持3.0,使用倒是不受影响)

安装

npm install pinia-plugin-persist --save --legacy-peer-deps

配置

main.ts

import './assets/main.css'
import 'element-plus/dist/index.css'
import { createApp } from 'vue'
import App from './App.vue'
import axios from 'axios'
import ElementPlus from 'element-plus'
import Router from './router/router.ts'
import { createPinia } from 'pinia'
import piniaPluginPersist from 'pinia-plugin-persist'

const pinia = createPinia()
const app = createApp(App)

app.config.globalProperties.$axios = axios
app.use(ElementPlus)
app.use(Router)
app.use(pinia)
pinia.use(piniaPluginPersist)// 持久化
app.mount('#app')

使用

userStore.ts

import {defineStore} from "pinia";

/**
 * 用户存储模块
 * 包含用户的基本信息和相关操作
 */
export const useUserStore = defineStore('user', {
  /**
   * 存储的状态
   * @returns 用户状态对象
   */
  state: () => ({
    name: '张三', // 用户名
    age: 18       // 用户年龄
  }),
  /**
   * 获取器
   */
  getters: {
    /**
     * 获取用户的年龄
     * @param state 当前状态
     * @returns 用户的年龄
     */
    getAge: (state) => state.age
  },
  /**
   * 动作(用于修改状态)
   */
  actions: {
    /**
     * 设置用户的年龄
     * @param age 新的年龄值
     */
    setAge(age: number) {
      this.age = age;
    }
  },
  /**
   * 持久化配置
   */
  persist: {
    enabled: true,
  }
});

以上再刷新就不会还原默认配置了


网站公告

今日签到

点亮在社区的每一天
去签到