本小节我们介绍如何嵌套使用 VueRouter。嵌套路由在日常的开发中非常常见,如何定义和使用嵌套路由是本节的重点。同学们在学完本节课程之后需要自己多尝试配置路由。
实际项目中的应用界面,通常由多层嵌套的组件组合而成。同样地,URL 中各段动态路径也按某种结构对应嵌套的各层组件,例如:
/article/vue /article/react
+------------------+ +-----------------+
| Article | | Article |
| +--------------+ | | +-------------+ |
| | Vue | | +------------> | | React | |
| | | | | | | |
| +--------------+ | | +-------------+ |
+------------------+ +-----------------+
代码块12345678
借助 vue-router,使用嵌套路由配置,就可以很简单地表达这种关系。 在上一小节中我们学习了如何配置一个路由信息:
{
path: '路由地址',
component: '渲染组件'
}
要配置嵌套路由,我们需要在配置的参数中使用 children 属性:
{
path: '路由地址',
component: '渲染组件',
children: [
{
path: '路由地址',
component: '渲染组件'
}
]
}
接下来我们对上一小节的例子来做一个改造:在文章页面,我们对文章进行分类,提供两个链接按钮 vue、react,点击可以跳转到对应的文章列表,具体代码示例如下:
实例演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<div>
<router-link to="/index">首页</router-link>
<router-link to="/article">文章</router-link>
</div>
<router-view></router-view>
</div>
</body>
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<script type="text/javascript">
const Index = Vue.component('index', {
template: '<div>Hello,欢迎使用慕课网学习 Vue 教程!</div>',
})
const Article = Vue.component('myArticle', {
template: `<div>
<div>
<router-link to="/article/vue">vue</router-link>
<router-link to="/article/react">react</router-link>
</div>
<router-view></router-view>
</div>`,
})
const VueArticle = Vue.component('vueArticle', {
template: `<ul><li>1. Vue 基础学习</li><li>2. Vue 项目实战</li></ul>`,
})
const ReactArticle = Vue.component('reactArticle', {
template: `<ul><li>1. React 基础学习</li><li>2. React 项目实战</li></ul>`,
})
const routes = [
{ path: '/index', component: Index },
{
path: '/article',
component: Article ,
children: [
{
path: 'vue',
component: VueArticle ,
},
{
path: 'react',
component: ReactArticle ,
}
]
}
]
const router = new VueRouter({
routes: routes
})
var vm = new Vue({
el: '#app',
router,
data() {
return {}
}
})
</script>
</html>
"运行案例" 可查看在线运行效果
代码解释: HTML 代码第 12-13 行,我们定义了两个跳转链接。 HTML 代码第 15 行,我们使用 <router-view></router-view> 组件来渲染匹配组件。 JS 代码第 5-7 行,我们定义了组件 Index。 JS 代码第 9-17 行,我们定义了组件 Article,组件内部使用 <router-link></router-link> 定义出来两个跳转链接,使用 <router-view></router-view> 来渲染匹配组件。 JS 代码第 19-21 行,我们定义了组件 VueArticle. JS 代码第 23-25 行,我们定义了组件 ReactArticle。 JS 代码第 27-43 行,我们定义了路由数组,在 ‘/article’ 中配置来嵌套路由 children JS 代码第 44-46 行,创建 router 实例,然后传 routes 配置。 JS 代码第 49 行,通过 router 配置参数注入路由。
在上述的例子中,我们通过 ‘/article/vue’ 来访问嵌套路由,但是有时候你可能不希望使用嵌套路径,这时候我们可以对上面例子中的配置信息做一点修改:
const routes = [
{ path: '/index', component: Index },
{
path: '/article',
component: Article ,
children: [
{
path: '/vueArticle',
component: VueArticle ,
},
{
path: '/reactArticle',
component: ReactArticle ,
}
]
}
]
以 ‘/’ 开头的嵌套路径会被当作根路径,因此,我们访问 ‘/vueArticle’ 就相当于访问之前的 ‘/article/vue’。
本节,我们带大家学习了 VueRouter 嵌套路由的使用方法,主要知识点有以下几点:
ue3 嵌套路由的使用和 Vue2 相差不大,主要的区别是 Vue3 的路由实例化使用了 createApp() 方法,所以实例化路由时需要传入根组件。另外,Vue3 的路由对象除了包含 Vue2 中的导航守卫、导航钩子和解析守卫等功能外,还新增了 meta prop 和 route prop。
在使用嵌套路由时,建议将路由按照功能模块进行分层,每一层代表一个主要的功能块,每个层级下的路由数量不要过多,一般建议不要超过 10 个,层级也不要超过 5 层。同时,根据实际业务需求,可以适当调整路由层级和数量,以达到更好的管理和使用效果。
import {
createRouter,
createWebHashHistory,
RouteRecordRaw
} from "vue-router";
// createWebHashHistory,createWebHistory
const routes: RouteRecordRaw[] = [
{
path: '/',
redirect: '/home',
},
{
path: '/home',
name: 'Home',
component: () => import('@/views/Home/index.vue'),
meta: {
title: 'Home Page',
roles: ['admin', 'admin1']
},
children: [
{
path: 'lx',
name: 'Lx',
component: () => import('@/views/Home/Lx.vue'),
// 也可以使用props传参方式接收传来的参数
props: (propsRouter) => {
// console.log('props >router', propsRouter)
// 可以return query 也可以return params支持两种传参方式
return propsRouter.query
},
// 多级嵌套 建议用query传参
children: [
{
path: 'childA',
name: 'ChildA',
component: () => import('@/views/Home/ChildA.vue'),
},
]
},
{
path: 'lxb/:id/:title', // 提前定义params参数(可以定义多个)
name: 'Lxb',
component: () => import('@/views/Home/Lxb.vue'),
},
]
},
]
export const router = createRouter({
// 路由的history模式,共有三种模式,
// createWebHistory、createWebHashHistory、createMemoryHistory
history: createWebHashHistory(),// history: createWebHistory(),
// 路由配置
routes,
// 是否严格匹配路由
strict: true,
// 路由跳转完成后,页面滚动行为
scrollBehavior: () => ({ left: 0, top: 0 }),
})
import { router } from './route/index'
import { createApp } from 'vue'
const app = createApp(App)
app.use(router).mount('#app')
<template>
<router-view />
</template>
<script>
import { defineComponent } from 'vue'
// vue3.0版本语法
export default defineComponent({
name: 'App',
})
</script>
<template>
<div class="home">
<h2>首页{{ title }}</h2>
<!-- 模拟有权限时显示 -->
<div v-if="roles.includes(role)">
<h2>嵌套路由</h2>
<router-link to="/home/lx">push跳转到/home/lx页面</router-link>
<br>
<!-- 加了/就要写全 /home/lxb -->
<router-link replace to="/home/lxb/id:2/title:102">push跳转到/home/lxb页面</router-link>
<router-view></router-view>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent, reactive, onMounted, toRefs, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
export default defineComponent({
name: 'Home',
setup() {
const router = useRouter()
const route: any = useRoute()
const state = reactive({
title: '',
role: '', // 我的当前角色
roles: [''],
routerGo: (path) => {
if (path === 'lx') {
// query传参可以用path 也可以用name: Lx
router.push({
path: path,
query: {
title: '101',
id: 1
}
})
// router.replace
} else {
// params传参只能用name
router.replace({
// path: path + '/id:2/title:102',
name: 'Lxb',
params: {
title: '102',
id: 2
}
})
}
},
})
onMounted(() => {
console.log('/home', route)
state.title = route.meta.title
state.roles = route.meta.roles
// 模拟一个接口
setTimeout(() => {
const res = {
code: 200,
data: {
token: '123456',
userName: '吴彦祖',
role: 'admin'
}
}
state.role = res.data.role
}, 0)
})
return {
...toRefs(state)
}
}
})
</script>
<style lang="less" scoped>
.home {
color: pink;
font-size: 14px;
}
</style>
<template>
<div style="font-size: 14px;">
<h2>我是练习b{{ route?.params?.title }}页面</h2>
<div>id:{{ route?.params?.id }}</div>
<button @click="routerGoBack">返回首页</button>
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// vue3.0语法
export default defineComponent({
name: 'Lxb',
setup() {
const route = useRoute()
const router = useRouter()
const state: any = reactive({
routerGoBack: () => {
router.replace('/home')
// 由replace跳转进来的不可以使用router.go(-1) 路由栈是空的》回不到上一个路由
},
})
onMounted(() => {
console.log(route)
})
return {
route,
...toRefs(state)
}
},
})
</script>
<template>
<div style="font-size: 14px;">
<h2>我是练习{{ title }}页面</h2>
<div>id:{{ id }}</div>
<div>props: {{ props }}</div>
<button @click="routerGoBack">返回上一页</button>
<br>
<button @click="routerGo('/home/lx/childA')">去子路由childA</button>
<!-- <router-view></router-view> -->
<router-view />
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, toRefs } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// vue3.0语法
export default defineComponent({
name: 'Lx',
props: {
id: {
type: String,
default: ''
},
title: {
type: String,
default: ''
},
},
setup(props) {
const route = useRoute()
const router = useRouter()
const state: any = reactive({
id: '',
title: '',
routerGoBack: () => {
router.go(-1) // go(-1)回到上一个路由
// 也可以用router.replace('/home')跳回指定页
},
routerGo: (path) => {
router.push(path)
}
})
onMounted(() => {
console.log('lx route', route)
console.log('lx props', props)
if (route.query) {
state.id = route.query.id
state.title = route.query.title
}
})
return {
props,
...toRefs(state)
}
},
})
</script>
<template>
<div style="font-size: 14px;background: skyblue;">
<h3>我是ChildA组件</h3>
<h3>route.query:{{ route.query }}</h3>
</div>
</template>
<script lang="ts">
import { defineComponent, onMounted, } from 'vue'
import { useRoute, useRouter } from 'vue-router'
// vue3.0语法
export default defineComponent({
name: 'ChildA',
setup() {
const router = useRouter()
const route = useRoute()
function goBack() {
router.go(-1)
}
onMounted(() => {
console.log(route)
})
// 可以在页面销毁前清除事件
// onUnmounted(() => {
// proxy.$mittBus.off('mittUserA')
// })
return {
route, goBack
}
},
})
</script>
嵌套一层的路由从原本/home跳入了/home/lxb 子路由页面,点击回到首页。
先去到了第一层/home/lx子路由页面,
再点击去子路由childA按钮>页面效果:
进到了嵌套的第二层/home/lx/childA子路由页面
点击可返回上一页/home/lx 再点击可回到/home首页。
欢迎关注我的原创文章:小伙伴们!我是一名热衷于前端开发的作者,致力于分享我的知识和经验,帮助其他学习前端的小伙伴们。在我的文章中,你将会找到大量关于前端开发的精彩内容。
学习前端技术是现代互联网时代中非常重要的一项技能。无论你是想成为一名专业的前端工程师,还是仅仅对前端开发感兴趣,我的文章将能为你提供宝贵的指导和知识。
在我的文章中,你将会学到如何使用HTML、CSS和JavaScript创建精美的网页。我将深入讲解每个语言的基础知识,并提供一些实用技巧和最佳实践。无论你是初学者还是有一定经验的开发者,我的文章都能够满足你的学习需求。
此外,我还会分享一些关于前端开发的最新动态和行业趋势。互联网技术在不断发展,新的框架和工具层出不穷。通过我的文章,你将会了解到最新的前端技术趋势,并了解如何应对这些变化。
我深知学习前端不易,因此我将尽力以简洁明了的方式解释复杂的概念,并提供一些易于理解的实例和案例。我希望我的文章能够帮助你更快地理解前端开发,并提升你的技能。
如果你想了解更多关于前端开发的内容,不妨关注我的原创文章。我会不定期更新,为你带来最新的前端技术和知识。感谢你的关注和支持,我们一起探讨交流技术共同进步,期待与你一同探索前端开发的奇妙世界!
#前端#
生成动态的HTML页面,页面中使用嵌入 Vue.js 语法可动态生成
1. {{xxxx}}双大括号文本绑定
2. v-xxxx以v-开头用于标签属性绑定,称为指令
双大括号语法{{}}
格式:{{表达式}}
作用:
使用在标签体中,用于获取数据
可以使用 JavaScript 表达式
一次性插值v-once
通过使用v-once指令,你也能执行一次性地插值,当数据改变时,插值处的内容不会更新
输出HTML指令v-html
格式:v-html='xxxx'
作用:
如果是HTML格式数据,双大括号会将数据解释为普通文本,为了输出真正的 HTML,你需要使用v-html指令。
Vue 为了防止 XSS 攻击,在此指令上做了安全处理,当发现输出内容有 script 标签时,则不渲染
XSS 攻击主要利用 JS 脚本注入到网页中,读取 Cookie 值(Cookie一般存储了登录身份信息),读取到了发送到黑客服务器,从而黑客可以使用你的帐户做非法操作。XSS 攻击还可以在你进入到支付时,跳转到钓鱼网站。
元素绑定指令v-bind
完整格式:v-bind:元素的属性名='xxxx'
缩写格式::元素的属性名='xxxx'
作用:将数据动态绑定到指定的元素上
事件绑定指令v-on
完整格式:v-on:事件名称="事件处理函数名"
缩写格式:@事件名称="事件处理函数名"注意:@后面没有冒号
作用:用于监听 DOM 事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h3>1、{{}}双大括号输出文本内容</h3>
<!-- 文本内容 -->
<p>{{msg}}</p>
<!-- JS表达式 -->
<p>{{score + 1}}</p>
<h3>2、一次性插值</h3>
<p v-once>{{score + 1}}</p>
<h3>3、指令输出真正的 HTML 内容 v-html</h3>
<p>双大括号:{{contentHtml}}</p>
<!--
v-html:
1、如果输出的内容是HTML数据,双大括号将数据以普通文本方式进行输出,为了输出真正HTML数据,就需要使用v-html指定
2、为了防止XSS攻击
-->
<p>v-html:<span v-html="contentHtml"></span></p>
<h3>4、v-bind属性绑定指令</h3>
<img v-bind:src="imgUrl">
<img :src="imgUrl">
<a :href="tzUrl">跳转</a>
<h3>5、事件绑定指令 v-on</h3> <input type="text" value="1" v-model="num"> <button @click='add'>点击+1</button> </div> <script src="./node_modules/vue/dist/vue.js"></script> <script> var vm = new Vue({ el: '#app', data: { msg: "菜园子", score: 100, contentHtml: '<span style="color:red">此内容为红色字体</span>', imgUrl: 'https://cn.vuejs.org/images/logo.png', tzUrl: 'https://www.baidu.com/', num : 10 }, methods: { add: function(){ console.log('add被调用') this.num ++ } }, }) </script></body></html>
git源码地址:https://github.com/caiyuanzi-song/vue-demo.git
*请认真填写需求信息,我们会在24小时内与您取得联系。