一、路由进阶
1.1 路由的封装抽离
main.js
import Vue from 'vue'
import App from './App.vue'
// 导入
import router from './router/index'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
router
}).$mount('#app')
src → router → index.js
//如果层级很深就很难找可以用绝对路径,用@表示从src出发
import Find from '@/views/Find'
import My from '@/views/My'
import Friend from '@/views/Friend'
// 重新导入一次
import Vue from 'vue'
import VueRouter from 'vue-router'
Vue.use(VueRouter) // VueRouter插件初始化
// 创建了一个路由对象
const router = new VueRouter({
// routes 路由规则们
// route 一条路由规则 { path: 路径, component: 组件 }
routes: [
{
path: '/find', component: Find },
{
path: '/my', component: My },
{
path: '/friend', component: Friend },
]
})
// 导出
export default router
1.2 声明式导航 - 导航链接
需要给类设置
.footer_wrap a.router-link-active {
background-color: purple;
}
总结
1.3 声明式导航 - 两个类名
1.4 声明式导航 - 跳转传参
目标:在跳转路由时, 进行传值
- 查询参数传参
- 动态路由传参
1. 查询参数传参
- ① 语法格式如下
to=“/path ?参数名=值” - ② 对应页面组件接收传递过来的值
$route.query.参数名
Home.vue
<template>
<div class="home">
<div class="logo-box"></div>
<div class="search-box">
<input type="text">
<button>搜索一下</button>
</div>
<div class="hot-link">
热门搜索:
<router-link to="/search?key=黑马程序员">黑马程序员</router-link>
<router-link to="/search?key=前端培训">前端培训</router-link>
<router-link to="/search?key=如何成为前端大牛">如何成为前端大牛</router-link>
</div>
</div>
</template>
<script>
export default {
name: 'FindMusic'
}
</script>
<style>
.logo-box {
height: 150px;
background: url('@/assets/logo.jpeg') no-repeat center;
}
.search-box {
display: flex;
justify-content: center;
}
.search-box input {
width: 400px;
height: 30px;
line-height: 30px;
border: 2px solid #c4c7ce;
border-radius: 4px 0 0 4px;
outline: none;
}
.search-box input:focus {
border: 2px solid #ad2a26;
}
.search-box button {
width: 100px;
height: 36px;
border: none;
background-color: #ad2a26;
color: #fff;
position: relative;
left: -2px;
border-radius: 0 4px 4px 0;
}
.hot-link {
width: 508px;
height: 60px;
line-height: 60px;
margin: 0 auto;
}
.hot-link a {
margin: 0 5px;
}
</style>
Search.vue
<template>
<div class="search">
<p>搜索关键字: {
{ $route.query.key }} </p>
<p>搜索结果: </p>
<ul>
<li>.............</li>
<li>.............</li>
<li>.............</li>
<li>.............</li>
</ul>
</div>
</template>
<script>
export default {
name: 'MyFriend',
created () {
// 在created中,获取路由参数
// this.$route.query.参数名 获取
console.log(this.$route.query.key);
}
}
</script>
<style>
.search {
width: 400px;
height: 240px