路由的基本使用
前言
1 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
2 创建路由new VueRouter(),接受的参数是一个对象
3 在实例化的对象里配置属性routes:[],这个数组里的对象包含path属性和component属性
4 path属性是url的地址,component属性就是显示的组件(传组件的对象)
5 创建的路由需要和vue实例关联一下
6 路由到的组件显示在哪个位置
提示:以下是本篇文章正文内容,下面案例可供参考
代码如下(示例):
<div id='app'>
<!-- 5、预留展示区域 -->
<router-view></router-view>
<router-view name="detail"></router-view>
<router-view name="mine"></router-view>
<router-link :to="{path:'/detail', query:{courseid:123,id:456} }">去详情1</router-link>
<router-link :to="{name:'my',params:{ids:789} }">去个人中心</router-link>
</div>
<template id="index">
<div>
首页
<a href="#/detail?coreseId=123">去详情a</a>
<!-- router-link标签可以设置to属性 -->
<router-link to="/detail">去详情</router-link>
<!-- 声明式的路由跳转 -->
<!-- 路由的跳转 传参 -->
<router-link :to="{path:'/detail', query:{courseid:123,id:456} }">去详情1</router-link>
<router-link :to="{name:'my',params:{ids:789} }">去个人中心</router-link>
<!-- 错误写法 -->
<!-- <router-link :to="{name:'my' }">去个人中心1</router-link> -->
<!-- 函数式 -->
<button @click="toDetail">toDetail</button>
<button @click="toMine">toMine</button>
</div>
</template>
<!-- 1. 声明路由的时候设置children,这是children是一个数组,数组里是路由对象
2. 这个children的组件就会渲染在它父组件的<router-view>中
-->
<template id="detail">
<div>
详情页
<router-view></router-view>
</div>
</template>
<template id="mine">
<div>
个人中心
</div>
</template>
<template id="play">
<div>
play
</div>
</template>
<template id="study">
<div>
study
</div>
</template>
let play = {
template: '#play'
}
let study = {
template: '#study'
}
let index = {
template: '#index',
methods: {
toDetail() {
console.log(1);
// this.$router.push('/detail')
this.$router.push({
path: '/detail',
query: {
id: 12312
}
})
},
toMine() {
this.$router.push({
name: 'my',
params: {
ids: 8908
}
})
}
}
}
let detail = {
template: '#detail',
created() {
console.log(this);
console.log(this.$route.query);
console.log(this.$route.query.courseid);
}
}
let mine = {
template: '#mine',
created() {
console.log(this);
console.log(this.$route.params.ids);
}
}
// 2、创建路由实例
const router = new VueRouter({
// 3、创建映射关系
routes: [
// 路由的重定向
{
path: '/',
redirect: '/index'
},
{
path: '/index',
// component: index
// 命名视图
components: {
default: index,
detail,
mine
}
},
{
path: '/detail',
component: detail,
// 路由嵌套
children: [
// path路径后不能加 /
{
path: 'play',
component: play
},
{
path: 'study',
component: study
}
]
},
{
path: '/mine/:ids',
name: 'my',
component: mine
}
],
// 配置 linkActiveClass: '自定义的类名'
linkActiveClass: 'active'
})
const vm = new Vue({
// 4、将路由实例挂载到vue实例上
// router: router,
router,
el: '#app',
data: {
},
methods: {
}
})