事件 window.onhashchange
当监听到hash发生了改变,该事件触发,执行事件后面设定的方法
demo 父组件
<template>
<div class="app">
<!-- 跳转子组件a -->
<a href="#/sona">sona</a>
<br />
<!-- 跳转子组件b -->
<a href="#/sonb">sonb</a>
<br />
<sona v-if="myHash == '#/sona'"></sona>
<sonb v-if="myHash == '#/sonb'"></sonb>
</div>
</template>
<script>
import sona from "./components/sona";
import sonb from "./components/sonb";
export default {
data() {
return {
myHash: ""
};
},
components: {
sona,
sonb
},
created() {
this.myHash = window.location.hash;
window.onhashchange = () => {
this.myHash = window.location.hash;
};
}
};
</script>
<style></style>
子组件a
<template>
<div class="sona">
sona组件
</div>
</template>
<script>
export default {};
</script>
<style>
.sona {
width: 400px;
height: 400px;
background-color: #f99;
}
</style>
子组件b
<template>
<div class="sonb">
sonb组件
</div>
</template>
<script>
export default {};
</script>
<style>
.sonb {
width: 600px;
height: 600px;
background-color: #f60;
}
</style>