Implementation Principle of Vue router view and router link
- 2021-11-01 02:18:36
- OfStack
Use
<div id="app">
<router-link to='home'> Home page </router-link>
<router-link to='about'> About </router-link>
<router-view a=1><router-view/>
</div>
router-view component
export default {
// Functional components do not have this Can't new There is no bi-directional data binding, which is usually used less, and is more suitable for presenting details pages. Because details pages only show operations such as no modification, functional components are lighter than stateful components.
functional:true,
render(h,{parent,data}){
parent The parent component represented by the app
data Is an inter-line attribute ( Above code a=1) You can also use the prop Transfer
let route = parent.$route;
let depth = 0;
data.routerView = true;
while(parent){
//$vnode It refers to virtual dom If app There is a virtual on the dom And this virtual dom Above routerView For true
if (parent.$vnode && parent.$vnode.data.routerView){
depth++;
}
parent = parent.$parent;
}
let record = route.matched[depth];
if(!record){
return h();
}
return h(record.component, data);
}
}
Implementation of router-link
export default {
props:{
to:{
type:String,
required:true
},
tag:{
type:String
}
},
render(h){
let tag = this.tag || 'a';
let handler = ()=>{
this.$router.push(this.to);
}
return <tag onClick={handler}>{this.$slots.default}</tag>
}
}