lyz自学笔记
前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、什么是动态路由
在某些情况下,一个页面的 path路径可能是不确定的,比如我们进入用户界面时,希望是如下路径:
- /user/aaaa 或 /user/bbbbb
- 除了前面的/user之外,后面还跟上了用户的ID
- 这种path和component的匹配关系,我能称之为动态路由(也是路由传递数据的一种方式)
二、使用动态路由
1、初始化项目后,在components中创建一个组价
<template>
<div>
<h2>我是用户界面</h2>
<p>我是用户的相关信息, 嘿嘿嘿</p>
</div>
</template>
<script>
export default {
name: "User",
}
</script>
<style scoped>
</style>
2、然后在路由对象中进行映射
import User from '../components/User’
const routes = [
{
path: '',
// redirect重定向
redirect: '/home'
},
{
path: '/home',
component: Home,
{
path:'/about'.
component: About
},
{
path:'/user',
component:User
}
}
]
3、在App.vue中使用
<template>
<div id="app">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<router-link to="/user">用户</router-link>
<router-view></router-view>
</div>
</template>
<script>
import Home from "./components/Home";
export default {
name: 'App'
}
</script>
<style>
</style>
4、但如果路由后面需要带参数的话就需要这样写了
(1)先需要在index.js文件中进行路由映射
import User from '../components/User’
const routes = [
{
path: '',
// redirect重定向
redirect: '/home'
},
{
path: '/home',
component: Home,
{
path:'/about'.
component: About
},
{
path:'/user',
component:User
},
{
path:'/user/:userId'
component:User
}
}
]
(2)然后在App.vue文件使用,在跳转的时候使用这种格式
:to="’/user/’+userId",把参数传递过去
<template>
<div id="app">
<router-link to="/home">首页</router-link>
<router-link to="/about">关于</router-link>
<router-link :to="'/user/'+userId">用户</router-link>
<router-view/>
</div>
</template>
<script>
import HomeNews from "./components/HomeNews";
import Home from "./components/Home";
export default {
name: 'App',
components: {Home, HomeNews},
data() {
return {
userId: 'zhangsan',
imgURL: 'http://www.baidu.com/logo.png'
}
},
methods: {
homeClick() {
this.$router.replace('/home')
},
aboutClick() {
this.$router.replace('/about')
}
}
</script>
<style>
</style>
3、参数传递过去后,要在User.vue组件接收和使用
<template>
<div>
<h2>我是用户界面</h2>
<p>我是用户的相关信息, 嘿嘿嘿</p>
<h2>{{userId}}</h2>
//其实也可以这样直接拿到
<h2>{{$route.params.id}}</h2>
</div>
</template>
<script>
export default {
name: "User",
computed:{
userId(){
//使用当前活跃路由的参数
this.$route.params.userId
}
}
}
</script>
<style scoped>
</style>
这样就可以拿到从路由传递过来的数据