前端路由模拟(hash值、Vue)
- 创建三个简易的子组件
<script type="text/x-template" id="home">
<div>
<h1>home</h1>
</div>
</script>
<script type="text/x-template" id="profile">
<div>
<h1>profile</h1>
</div>
</script>
<script type="text/x-template" id="cart">
<div>
<h1>cart</h1>
</div>
</script>
const home = {
template: '#home'
}
const profile = {
template: '#profile'
}
const cart = {
template: '#cart'
}
- 父组件
<div id="app">
<a href="#/home">Home</a>
<a href="#/profile">profile</a>
<a href="#/cart">cart</a>
<component :is="comName"></component>
</div>
const vue = new Vue({
el: '#app',
data: {
comName: 'home'
},
components: {
home,
profile,
cart
},
methods: {
hChange() {
window.onhashchange = () => {
this.comName = location.hash.slice(2);
return;
}
}
}
})
- 点击
a标签
会将url上添加/#/对应组件名
的锚点,我们可以通过window.onhashChange事件方法
来监听loacation.hash
的变化,变化就会触发。
- 我们只用将
<compontent>标签上的is属性
修改为对应的组件名就可以了(一定要是字符串类型的组件名)
window.onhashChange事件方法
最后接箭头函数,因为this
的指向问题。
前端路由模拟(history、Vue)
- 跟在Vue用
mode:history
一样的情况跳转路由之后不可以刷新,不然他就会请求原本路径+‘/xx’
的文件了。 - 子组件
<script type="text/x-template" id="home">
<div>
<h1>home</h1>
</div>
</script>
<script type="text/x-template" id="profile">
<div>
<h1>profile</h1>
</div>
</script>
const home = {
template: '#home'
}
const profile = {
template: '#profile'
}
const cart = {
template: '#cart'
}
- 父组件
<div id="app">
<a href="javascript:void(0)" @click="changeUrl('home')">Home</a>
<a href="javascript:void(0)" @click="changeUrl('profile')">profile</a>
<component :is="comName"></component>
</div>
const vue = new Vue({
el: '#app',
data: {
comName: 'home'
},
components: { // 组件不用说
home,
profile
},
methods: {
changeUrl(com) {
// url路径修改但是不会请求资源和刷新
history.pushState(null, null, this.LocationHref + com);
this.comName = com; // 修改component标签中的is属性达到子组件的替换
}
},
mounted() {
this.LocationHref = location.href + '/'; // 拿到当前页面的href
}
})
- 当
mode: history
刷新时之所以会出现访问不到页面的原因就是history.pushState()
导致url
改变之后,刷新会请求当前路径下的资源
,而我们当前路径
根本没有对应资源,只是我们写的路由而已,所以刷新之后请求不到对应的页面。 hash
可以刷新的原因是不会请求/#/xx
这样的锚点当做资源。history模式
下只能在服务器路径下即http://127.0.0.1/xxx
这种情况下,而无法在电脑目录上运行file:///E:/xxx.html
在这种目录下,history模式
下url
改变会请求对应目录下的资源。
每天一个脱发小技巧 —— 菜鸡