1.平级路由及子路由添加:
import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Hello from '@/components/Hello'
import Hello1 from '@/components/Hello1'
import Hello2 from '@/components/Hello2'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/',
name: 'HelloWorld',
component: HelloWorld
},
{
path: '/hello',
name: 'Hello',
component: Hello,
children: [
{
path: 'hello1',
name: 'Hello1',
component: Hello1
},
{
path: 'hello2',
name: 'Hello2',
component: Hello2
}
]
}
]
})
2.路由之间跳转及传参
a)可以通过下面代码进行路由的跳转和传参(本页面跳转和打开新页面)
goOn:function(){
this.$router.push({name:"Hello",query:{id:15}});
},
goOn2:function(){
window.open("http://192.168.1.232:8080/#/hello?id=15");
},
b) 目标页面通过下面代码获取参数
msg: this.$route.query.id
3.如何在父组件中展示子组件
<template>
<div>
<div class="hello">
{{msg}}
</div>
<button @click="goHello1">进入hello1</button>
<button @click="goHello2">进入hello2</button>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Hello',
data () {
return {
msg: this.$route.query.id
}
},
methods:{
goHello1:function(){
this.$router.push("/hello/hello1");
},
goHello2:function(){
this.$router.push("/hello/hello2");
}
}
}
</script>
其中<router-view></router-view>区域就是用于子组件的展示。
4.父子组件中的传参
a)父组件向子组件传参
//父组件
<hello4 :giveson="toChildParam" @getSonData="getSonData">
</hello4>
data () {
return {
toChildParam:44444
}
},
//子组件
<div class="hello">
{{giveson}}
</div>
props:[
"giveson"
],
b)子组件向父组件传参
//父组件
<hello4 @getSonData="getSonData">
</hello4>
methods:{
getSonData:function(sondata){
this.msg = sondata;
}
},
//子组件
<button @click="giveFather">向父级传参</button>
methods:{
giveFather:function(){
this.$emit("getSonData","111111");
}
}
5.插槽
a)父页面
<hello4>
<div>dhjksjdjsddjdj</div>
</hello4>
b)子页面
<slot></slot>