Vue-router原理:7、创建router-view
组件
router-view
组件就是一个占位符。当根据路由规则找到组件后,会渲染到router-view
的位置。
在initComponents
方法中创建router-view
组件
//该方法需要一个参数为Vue的构造函数。
//当然也可以使用全局的_Vue.
initComponents(Vue) {
Vue.component("router-link", {
props: {
to: String,
},
// template: '<a :href="to"><slot></slot></a>',
render(h) {
return h(
"a",
{
attrs: {
href: this.to,
},
},
[this.$slots.default]
);
},
});
const self = this;//修改this的指向
Vue.component("router-view", {
render(h) {
//根据当前的路径从routeMap中查找对应的组件.
const component = self.routeMap[self.data.current];
//将组件转换成虚拟dom
return h(component);
},
});
}
下面,我们可以测试一下效果。
当我们单击链接的时候,发现了浏览器进行了刷新操作。表明向服务器发送了请求,而我们单页面应用中是不希望向服务器发送请求。
修改后的initComponents
方法如下:
//该方法需要一个参数为Vue的构造函数。
//当然也可以使用全局的_Vue.
initComponents(Vue) {
Vue.component("router-link", {
props: {
to: String,
},
// template: '<a :href="to"><slot></slot></a>',
render(h) {
return h(
"a",
{
attrs: {
href: this.to,
},
on: {
click: this.clickHandler,
},
},
[this.$slots.default]
);
},
methods: {
clickHandler(e) {
history.pushState({}, "", this.to);
this.$router.data.current = this.to;
//阻止向服务器发送器。
e.preventDefault();
},
},
});
const self = this;
Vue.component("router-view", {
render(h) {
//根据当前的路径从routeMap中查找对应的组件.
const component = self.routeMap[self.data.current];
//将组件转换成虚拟dom
return h(component);
},
});
}
给a
标签添加了单击事件。