VUE monitor current routing listener watch

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/qq_35713752/article/details/102686924

Listener:

You can use the listener, in response to changes in the data, such as routing, and the value of the data page, when they can be written in a corresponding change in the processing logic listener.

Use the listener is simple: watch object is a listener only when the value of listeners has changed it is executed.

data() {
  return {
    msg: ''
  }
},
watch:{
  msg:function(){
    this.msg = '我改变了,新的msg为:'+msg;
  }
}

Code analysis: msg affirmed in data variable is an empty string, creating a listening watch on the inside msg listener object, when the value of the msg, msg listening function will be executed.

 

Let's listen for a complete code demo route changes: 

Requirements:
In addition to the home page, navigation bar should show [a] return on each page.

Solution:
In the navigation bar [return] components inside, watch the object by listening whether the current route for the home page, and then determine the status display

Code:

<template>
  <div id="back" v-if="isShowBack">
    <div class="back_box" @click="toBack()">
      <span class="left_arrow">
        <img src="../../../static/images/icon_arrow_bottom_left.png" />
      </span>
    </div>
  </div>
</template>
 
<script>
  var that;
  export default {
    data() {
      return {
        msg: '',
        isShowBack:false
      }
    },
    methods: {
      toBack() {
        console.log('点击了返回')
        this.$router.go(-1);
      }
    },
    watch:{
      '$route':function(){
        that = this;
        console.log('watch里面',that.$route.name);
        if(that.$route.name == 'HomeNew'){
          that.isShowBack = false;
        }else{
          that.isShowBack = true;
        }
      }
    }
  }
</script>
 
<style scoped="scoped">
  .back_box {
    width: 100%;
    height: 30px;
    background: #f1f1f1;
  }
 
  .left_arrow {
    width: 22px;
    display: inline-block;
    transform: rotate(90deg);
    margin-top: 4px;
    margin-left: 4px;
  }
 
  .left_arrow img {
    width: 100%;
  }
</style>

 

Guess you like

Origin blog.csdn.net/qq_35713752/article/details/102686924