【卷起来】VUE3.0教程-08-路由管理

在Vue中,我们可以通过vue-router路由管理页面之间的关系。

Vue Router是Vue.js的官方路由,它与Vue.js核心深度集成,让用Vue.js构建单页应用变得轻而易举。

🌲 在Vue中引入路由

  • 安装路由
npm install --save vue-router

  • 建立三个vue组件

<template>
    <h1>关于我们</h1>
</template>

<script setup>
</script>
<template>

    <h1>管理系统主页</h1>
</template>
<template>
    <h1>展示消息</h1>
</template>
  • 配置独立的路由文件

在src中新建一个文件夹router,在其中新建一个index.js

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

const routes = [
    {
        path:'/',
        name:'home',
        component:()=> import('../components/HomeView.vue')
    },{
        path:'/about',
        name:'about',
        component:()=> import('../components/AboutDemo.vue')
    },{
        path:'/show',
        name:'show',
        component:()=> import('../components/ShowDemo.vue')
    }
]

const router=createRouter({
    history:createWebHistory() // 去掉请求后面的#
    ,routes
})

export default router;
  • 在main.js中挂载路由
import axios from 'axios'

import { createApp } from 'vue'
import App from './App.vue'
// 挂载目录
import router from './router'

const app = createApp(App)
app.config.globalProperties.$axios = axios
app.use(router)
app.mount('#app')
  • 指定路由入口和路由跳转
<script setup>

  
</script>

<template>
  <!-- <AxiosDemo></AxiosDemo> -->
  <!-- <RequestAxiosDemo></RequestAxiosDemo> -->
  <div>
    <nav>
      <!--指定路由显示入口和跳转路径 -->
      <RouterLink to="/">Home</RouterLink> | 
      <RouterLink to="/about">About</RouterLink> | 
      <RouterLink to="/show">Show</RouterLink>
    </nav>
  </div>
  <div>
    <!--路由入口  -->
    <RouterView></RouterView>
    <!-- <router-view></router-view> -->
  </div>
 
</template>


  • 配置好后,可以使用<router-view> 或者<RouterView>指定路由入口
  • 可以使用<router-link> 或者<RouterLink> 指定路由跳转

🌲 路由传参

页面跳转过程中,是可以携带参数的,这也是很常见的业务

比如:在一个列表项,点击进入查看每个列表项的详情

  • 第一步:在路由配置中指定参数的key
{
    path:'/hero/:id',
    name:"delete",
    component:()=>import("../components/DeleteDemo.vue")
}
  • 第二步:在跳转过程中携带参数
<nav>
  <RouterLink to="/">Home</RouterLink> | 
  <RouterLink to="/about">About</RouterLink> | 
  <RouterLink to="/show">Show</RouterLink>|
  <router-link :to="{name:'delete', params: {id:23}}"> 删除数据</router-link>  
</nav>  
  • 第三步:在详情页面读取路由携带的参数:
    • 模板中读取: this.$route.params.id }
template>
    <h1>删除消息</h1>
    <!-- <div>{{ result }}</div> -->
    <div >{{ this.$route.params.id }}</div>
</template>
    • js中读取:route.params.id
<script setup>
    import axios from 'axios';
    import { reactive,ref } from 'vue';
  import router  from '../router'
    import { useRoute } from 'vue-router';
    //获取通过函数获取route对象
    const route = useRoute()
    const result = reactive({})
    axios.delete("/api/hero/"+route.params.id).then(res=>{
        result.value = res.data
        console.log(res.data)
      // 路由跳转:类似于Servlet中的重定向
        router.push("/show")
    })
</script>

完整案例代码:

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


const routes = [
    {
        path:'/',
        name:'home',
        component:()=> import('../components/HomeView.vue')
    },{
        path:'/about',
        name:'about',
        component:()=> import('../components/AboutDemo.vue')
    },{
        path:'/show',
        name:'show',
        component:()=> import('../components/ShowDemo.vue')
    },{
        path:'/hero/:id',
        name:"delete",
        component:()=>import("../components/DeleteDemo.vue")
    }
]

const router=createRouter({
    history:createWebHistory() // 去掉请求后面的#
    ,routes
})

export default router;
<template>
    <h1>删除消息</h1>
    <!-- <div>{{ result }}</div> -->
    <div >{{ this.$route.params.id }}</div>
</template>

<script setup>
    import axios from 'axios';
    import { reactive,ref } from 'vue';
    import router  from '../router'
    import { useRoute } from 'vue-router';
    //获取通过函数获取route对象
    const route = useRoute()
    const result = reactive({})
    axios.delete("/api/hero/"+route.params.id).then(res=>{
        result.value = res.data
        console.log(res.data)
        
        // 路由跳转:类似于Servlet中的重定向
        router.push("/show")
    })
</script>

<script setup>

  
</script>

<template>
  <!-- <AxiosDemo></AxiosDemo> -->
  <!-- <RequestAxiosDemo></RequestAxiosDemo> -->
  <div>
    <nav>
      <RouterLink to="/">Home</RouterLink> | 
      <RouterLink to="/about">About</RouterLink> | 
      <RouterLink to="/show">Show</RouterLink>|
      <router-link :to="{name:'delete', params: {id:26}}"> 删除数据</router-link>
      
    </nav>  
  </div>
  <div>
    <RouterView></RouterView>
    <!-- <router-view></router-view> -->
  </div>
 
</template>


🌲VUE的状态管理(VUEX)

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式 + 库。它采 用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。

简单来说,状态管理可以理解成为了更方便的管理组件之间的数据交互,提供了一个集中式的管理方案,任何组件都可以按照指定的方式进行读取和改变数据

🌿 引入Vuex的步骤

第一步:安装VueX

npm install --save vuex

第二步:配置Vuex文件

在src目录下,新建一个store文件夹,并在其中新建一个index.js,内容如下:


import {createStore} from 'vuex'

export default createStore({
    state:{
        // 当下状态管理中,存的数据
        counter:20
    }
})

第三步,在main.js中引入vuex

import axios from 'axios'

import { createApp } from 'vue'
import App from './App.vue'
// 挂载路由目录
import router from './router'
//引入状态管理
import store from './store'

const app = createApp(App)
app.config.globalProperties.$axios = axios
// 使用路由
app.use(router)
// 使用状态管理
app.use(store)
app.mount('#app')

第四步:在需要的位置获取状态管理中的数据

  • 在模板中获取:{{$store.state.counter  }}
  • 在js中获取: computed(() => store.state.counter)

具体写法:


<template>
    <h1>关于我们</h1>
    <!-- 在模板中获取状态管理中存的值 -->
    <p>当下访问了{{$store.state.counter  }}"次"</p>
    <p>当下访问了{{counter }}"次"</p>
</template>

<script setup>
    import { computed } from 'vue';
    // 在js中获取状态管理中存的值
    import { useStore } from "vuex"
    const store = useStore()
    // 需要通过计算属性
    const counter = computed(() => store.state.counter)
    
</script>

🌿 Getter

对Vuex中的数据进行过滤


import {createStore} from 'vuex'

export default createStore({
    state:{
        // 当下状态管理中,存的数据
        counter:18
    },
    getters:{
        getCount(state){
            return state.counter>18?state.counter:
              "当前访问人数太少,才"+state.counter
        }
    }
})

getter的访问方式:


<template>
    <h1>关于我们</h1>
    <!-- 在模板中获取状态管理中存的值 -->
    <p>当下访问了{{$store.getters.getCount  }}"次"</p>
    <p>当下访问了{{counter }}"次"</p>
</template>

<script setup>
    import { computed } from 'vue';
    // 在js中获取状态管理中存的值
    import { useStore } from "vuex"
    const store = useStore()
    // 需要通过计算属性
    const counter = computed(() => store.getters.getCount)
    
</script>

🌿 Mutaion

更改 Vuex 的 store 中的状态的唯一方法是提交 mutation。Vuex中的 mutation 非常类似于事件:每个 mutation 都有一个字符串的事件类型 (type)和一个回调函数 (handler)。这个回调函数就是我们实际进行状态更改的地方,并且它会接受 state 作为第一个参数.


import {createStore} from 'vuex'

export default createStore({
    state:{
        // 当下状态管理中,存的数据
        counter:18
    },
    getters:{
        getCount(state){
            return state.counter>18?state.counter:"当前访问人数太少,才"+state.counter
        
        }
    },
    mutations:{
        setCounter(state,num){
            state.counter += num
        }
    }
})

在js中调用修改数据的方法


<template>
    <h1>关于我们</h1>
    <!-- 在模板中获取状态管理中存的值 -->
    <p>当下访问了{{$store.state.counter  }}次</p>
    <!-- <p>当下访问了{{counter }}"次"</p> -->
 
</template>

<script setup>
    import { computed } from 'vue';
    // 在js中获取状态管理中存的值
    import { useStore } from "vuex"
    const store = useStore()
    // 需要通过计算属性
    // const counter = computed(() => store.getters.getCount)
    
    // 修改count属性值
    store.commit("setCounter",20)     
</script>

在另一个vue文件中访问状态管理的值,看是否能正常访问到修改后的值

<template>

    <h1>管理系统主页</h1>

    <p>当下访问了{{$store.state.counter  }}次</p>
</template>

<script setup>

</script>

🌿 Action

Action 类似于 mutation,不同在于:

  • Action 提交的是 mutation,而不是直接变更状态
  • Action 可以包含任意异步操作

import axios from 'axios'
import {createStore} from 'vuex'

export default createStore({
    state:{
        // 当下状态管理中,存的数据
        counter:18
    },
    getters:{
  		  //自定义的方法名
        getCount(state){
            return state.counter>18?state.counter:"当前访问人数太少,才"+state.counter
        
        }
    },
    mutations:{
       //自定义的方法名
        setCounter(state,num){
            state.counter += num
        }
    },
    actions:{
        //自定义的方法名
        asyncSetCount({commit}){
            axios.get("http://iwenwiki.com/api/generator/list.php")
                .then(res => {
                    console.log(res.data)
                    commit("setCounter",res.data[0])
                })
        }
    }
})

在js中调用自定义的actions方法:

store.dispatch("asyncSetCount")


<template>
    <h1>关于我们</h1>
    <!-- 在模板中获取状态管理中存的值 -->
    <p>当下访问了{{$store.state.counter  }}次</p>
    <!-- <p>当下访问了{{counter }}"次"</p> -->
 
</template>

<script setup>
    import { computed } from 'vue';
    // 在js中获取状态管理中存的值
    import { useStore } from "vuex"
    const store = useStore()
    // 需要通过计算属性
    // const counter = computed(() => store.getters.getCount)
    
    // 修改count属性值
    // store.commit("setCounter",20)

    store.dispatch("asyncSetCount")
  
    
</script>

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mfbz.cn/a/874835.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

详聊LLaMa技术细节:LLaMA大模型是如何炼成的?

本文介绍来自 Meta AI 的 LLaMa 模型&#xff0c;类似于 OPT&#xff0c;也是一种完全开源的大语言模型。LLaMa 的参数量级从 7B 到 65B 大小不等&#xff0c;是在数万亿个 token 上面训练得到。值得一提的是&#xff0c;LLaMa 虽然只使用公共的数据集&#xff0c;依然取得了强…

读论文-《基于计算机视觉的工业金属表面缺陷检测综述》

文章目录 1. 背景1.1 工业需求1.2 传统方法的局限1.3 计算机视觉技术的优势 2. 技术流程2.1 光学成像2.1.1照明方式2.1.2 缺陷和背景特性 2.2 图像预处理2.3 缺陷检测2.4 结果分析和决策 3. 关键算法3.1 光学成像技术相关算法3.2 图像预处理相关算法3.2.1 图像增强3.2.2特征提取…

【JS】将class转为构造函数需要注意的细节

前言 将 class 转为构造函数看似很简单&#xff0c;但作为封装者&#xff0c;有很多注意事项 class Person {constructor(name) {this.name name;}fn() { console.log(this.name); } }实现 初步转化如下&#xff1a; function Person() {this.name name } Person.prototy…

网络学习-eNSP配置VRRP

虚拟路由冗余协议(Virtual Router Redundancy Protocol&#xff0c;简称VRRP) VRRP广泛应用在边缘网络中&#xff0c;是一种路由冗余协议&#xff0c;它的设计目标是支持特定情况下IP数据流量失败转移不会引起混乱&#xff0c;允许主机使用单路由器&#xff0c;以及即使在实际…

二百六十三、Java——IDEA项目打成jar包,然后在Linux中运行

一、目的 在用Java对原Kafka的JSON字段解析成一条条数据&#xff0c;然后写入另一个Kafka中&#xff0c;代码写完后打成jar包&#xff0c;放在Linux中&#xff0c;直接用海豚调度运行 二、Java利用fastjson解析复杂嵌套json字符串 这一块主要是参考了这个文档&#xff0c;然…

如何进行DAP-seq的数据挖掘,筛选验证位点

从样本准备到寄送公司&#xff0c;每一天都在“祈祷”有个心仪的分析结果&#xff0c;终于在这天随着邮件提示音的响起&#xff0c;收到了分析结果...... 分析前工作 爱基在进行数据分析之前&#xff0c;会有两次质控报告反馈给老师们。第一个&#xff0c;基因组DNA的提取质控…

Django路由访问及查询数据

1、在应用模块下&#xff0c;创建urls文件&#xff0c;用来存放访问路由 2、在项目总访问url里面注册路由 3、在view文件里&#xff0c;定义方法参数 from django.core import serializers from django.db import connection from django.http import HttpResponse, JsonRespo…

什么是线程池?从底层源码入手,深度解析线程池的工作原理

导航&#xff1a; 【Java笔记踩坑汇总】Java基础JavaWebSSMSpringBootSpringCloud瑞吉外卖/谷粒商城/学成在线设计模式面试题汇总性能调优/架构设计源码解析 目录 一、什么是线程池&#xff1f; 1.1 基本介绍 1.2 创建线程的两种方式 1.2.1 方式1&#xff1a;自定义线程池…

NASA数据集:高级星载热发射和反射辐射计(ASTER)1B 级快速传感器辐射度登记全球数据产品

目录 简介 代码 引用 网址推荐 0代码在线构建地图应用 机器学习 ASTER L1B Registered Radiance at the Sensor V003 ASTER 加急 L1B 登记传感器 V003 的辐照度 简介 高级星载热发射和反射辐射计&#xff08;ASTER&#xff09;1B 级快速传感器辐射度登记全球数据产品是…

AIGC简化文件管理:Python自动重命名Word和PDF文件

1.背景 大家应该也有遇到&#xff0c;自己电脑有很多文件命名不合理的文件&#xff0c;比如&#xff1a;文件1、想法3 &#xff0c;当你长时间再看到这个文件的时候&#xff0c;已经很难知道文件内容。 今天我们将借助AIGC的编码能力&#xff0c;帮我们生成一个批量改文件名的…

语法基础课第五节字符串(知识点+题目)

字符串是计算机与人类沟通的重要手段。 1. 字符与整数的联系——ASCII码 每个常用字符都对应一个-128 ~ 127的数字&#xff0c;二者之间可以相互转化。注意&#xff1a;目前负数没有与之对应的字符。&#xff08;英文&#xff09; #include <iostream>using namespace…

Unity让摄像机跟随物体的方法(不借助父子关系)

在Unity中&#xff0c;不使用子对象的方式让相机跟随物体移动&#xff0c;我们通过编写脚本来实现。下面放一个从工程中摘出来的的C#脚本示例&#xff0c;用于将相机绑定到一个Target对象上并跟随其移动&#xff1a; using UnityEngine; public class FollowCamera : MonoBeh…

Python | Leetcode Python题解之第400题第N位数字

题目&#xff1a; 题解&#xff1a; class Solution:def findNthDigit(self, n: int) -> int:d, count 1, 9while n > d * count:n - d * countd 1count * 10index n - 1start 10 ** (d - 1)num start index // ddigitIndex index % dreturn num // 10 ** (d - d…

DroidBot-GPT: GPT-powered UI Automation for Android论文学习

本文介绍了DroidBot GPT&#xff0c;这是一种利用类似GPT的大型语言模型&#xff08;LLM&#xff09;自动化与Android移动应用程序交互的工具。给定所需任务的自然语言描述&#xff0c;DroidBot GPT可以自动生成并执行导航应用程序以完成任务的操作。它的工作原理是将应用程序G…

LabVIEW软件,如何检测连接到的设备?

在LabVIEW软件中&#xff0c;检测连接到的设备通常是通过NI提供的硬件驱动和相关工具来完成的。以下是几种常见的检测设备的方法&#xff1a; 1. 使用NI MAX&#xff08;Measurement & Automation Explorer&#xff09; 打开NI MAX&#xff1a;LabVIEW设备管理通常通过NI …

完整指南:CNStream流处理多路并发框架适配到NVIDIA Jetson Orin (四) 运行、调试、各种问题解决

目录 1 调试jetson-mpeg视频解码模块 1.1 修改config.json 1.2 Picture size 0x0 is invalid 1.3 Process(): Send package failed. Maximum number of attempts reached 1.4 Picture size 2239821608x65535 is invalid 1.5 保存h264文件解码之后的测试图片 1.6 保存RTS…

【CanMV K230 AI视觉】 人体检测

【CanMV K230 AI视觉】 人体检测 人体检测 动态测试效果可以去下面网站自己看。 B站视频链接&#xff1a;已做成合集 抖音链接&#xff1a;已做成合集 人体检测 人体检测是判断摄像头画面中有无出现人体&#xff0c;常用于人体数量检测&#xff0c;人流量监控以及安防监控等。…

“版权护航·星影计划”暨电影《末代天师》发布仪式

2024 年 9 月 10 日&#xff0c;由华纳星辰&#xff08;北京&#xff09;文化传媒有限公司与浙江焱煌影视文化传媒有限公司共同主办的 “版权护航・星影计划” 暨网络电影《末代天师》新闻发布会&#xff0c;在北京渔阳饭店世纪宴会厅华彩盛启。 北京影视艺术学会会长张连生、中…

springboot luttuc redis 集成protobuf,手动序列化反序列化

前置需知&#xff1a; 1.本文章和网上大部分博客配置不太一样&#xff0c;各位看官要分析一下自己的需求。集成protobuf 本文章主要是手动调用protobuf的序列化方法&#xff0c;而不是交由springboot 去做&#xff0c;会偏向原生java 使用方式 2.由于为了和公司其他的项目达成…

每日OJ_牛客_合唱团(打家劫舍dp)

目录 牛客_合唱团&#xff08;打家劫舍dp&#xff09; 解析代码1 解析代码2 牛客_合唱团&#xff08;打家劫舍dp&#xff09; 合唱团__牛客网 有 n 个学生站成一排&#xff0c;每个学生有一个能力值&#xff0c;牛牛想从这 n 个学生中按照顺序选取 k 名学生&#xff0c;要求…