vue-编程式跳转、组件裁减、定时器操作

路由跳转

路由跳转除了常用的在模板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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值