当前位置:网站首页>Resolve the conflict between computed attribute and input blur event

Resolve the conflict between computed attribute and input blur event

2022-04-23 14:40:00 Feather_ seventy-four

background : The search box is reused on the home page and search page , The search content of the home page needs to be transferred to the search page and displayed in the search box . The mode of transmission is through this.$router.push Add query Field .

<template>
  <div class="index-container">
    <a-input-search class="input-shape" v-model="searchInfo" placeholder="Search" @search="searchPaper(sendSearchInfo)" size="large" />
  </div>
</template>
export default {
    
  data() {
    
    return {
    
      sendSearchInfo: ''
    };
  },
  methods: {
    
    searchPaper(sendSearchInfo) {
    
      this.$router.push({
    
        path: '/search?',
        query: {
    
          info: sendSearchInfo
        }
      });
    }
  },
  computed: {
    
    searchInfo: {
    
      get() {
    
        return this.$route.query.info;
      },
      set(val) {
    
        this.sendSearchInfo = val;
      }
    }
  }
};

problem : stay input The data entered in will disappear when it loses focus
reason : When the page is initialized, it will execute get(), No longer perform , Every time you enter data, you execute set(). During the inspection, put the event in the listener blur Get rid of , That would not have happened . But printed onblur yes null, So it can't be removed . So it's the problem of data return .
resolvent :

export default {
    
  data() {
    
    return {
    
      sendSearchInfo: ''
    };
  },
  methods: {
    
    searchPaper(sendSearchInfo) {
    
      this.$router.push({
    
        path: '/search?',
        query: {
    
          info: sendSearchInfo
        }
      });
    }
  },
  computed: {
    
    searchInfo: {
    
      get() {
    
        //  because get involves this.sendSearchInfo, So every time set Will trigger get
        if (this.sendSearchInfo != '') {
    
          return this.sendSearchInfo;
        } else {
    
          return this.$route.query.info;
        }
      },
      set(val) {
    
        this.sendSearchInfo = val;
      }
    }
  }
};

版权声明
本文为[Feather_ seventy-four]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231435193327.html