路由跳转
路由跳转除了常用的在模板template编写router-link外,还可以在JS代码中进行跳转。
模板声明式:
模块编程式:router.push(…)
例:登入页登入完成自动跳回首页
<template>
<div>
倒计时:{{num}}
<button @click="back">首页</button>
</div>
</template>
<script>
export default {
data(){
return{
num:5
}
},
methods:{
back(){
this.$router.push({path:'/index'})
}
},
mounted(){
var _this = this,timer
timer = setInterval(function(){
if(_this.num == 0){
clearInterval(timer)
_this.$router.push({path:'/index'})
}else{
_this.num--
console.log(_this.num)
}
},1000)
}
}
</script>
组件裁减
<template>
<div id="app">
// 加if判断
<div v-if="headerShow">
<router-link to='/index'>主页</router-link>
<router-link to='/login'>登入</router-link>
<router-link to='/navslice'>裁剪</router-link>
</div>
<router-view v-wechat-title='$route.meta.title'/>
</div>
</template>
<script>
export default {
name: 'App',
data (){
return{
headerShow:true
}
},
watch:{
$route(to,from){
if(to.path == '/navslice'){
this.headerShow = false
}else{
this.headerShow = true
}
}
},
// 解决刷新之后头部又出现的问题
mounted(){
if(this.$route.path == "/navslice"){
this.headerShow = false
}
}
}
</script>
定时器操作
以上案例:
1.登入页登入完成自动跳回首页,在else里面console.log(_this.num)
2.当不是自动倒计时为零时返回,而是手动返回时。你会发现倒计仍然会打印到0停止
3.解决方案
<script>
export default {
data(){
return{
num:5,
// 定义定时器
timer:null
}
},
methods:{
back(){
this.$router.push({path:'/index'})
}
},
mounted(){
var _this = this
// 给data中的timer绑定定时器
_this.timer = setInterval(function(){
if(_this.num == 0){
clearInterval(timer)
_this.$router.push({path:'/index'})
}else{
_this.num--
console.log(_this.num)
}
},1000)
},
// 实例销毁之前清除定时器,data中的timer赋值为null
beforeDestroy(){
clearInterval(this.timer)
this.timer =null
}
}
</script>