鍍金池/ 問答/HTML/ 為什么我這個vue代碼里的watch(偵聽器)不起作用?

為什么我這個vue代碼里的watch(偵聽器)不起作用?

  import axios from 'axios';

  export default {
    name: 'Search',
    props: {
      requireType: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        searchModal: {
          select: 'weibo',
          value: '',
        },
        require: this.requireType,
      };
    },
    methods: {
      search() {
        if (this.require === 'focused') {
          axios.get('./static/hotRadeFocused.json')
            .then((response) => {
              this.$emit('getData', response.data);
            });
        }
        if (this.require === 'weibo') {
          axios.get('./static/hotRadeWeibo.json')
            .then((response) => {
              this.$emit('getData', response.data);
            });
        }
      },
    },
    watch: {
      require: function (val) {
        this.search();
      },
    },
    beforeMount() {
      this.search();
    },
  };
回答
編輯回答
遺莣

如果你的requireType是個對象才可以。字符串類型的話,是賦值操作,你watch肯定是不管用的
直接watch requireType就好

2018年9月7日 17:44
編輯回答
遺莣

對于原始類型變量,watch可以直接監(jiān)聽,對于引用類型變量,采用深度監(jiān)聽。


    watch: {
        require: {
          handler: function ( newVal, oldVal ) {
              this.search();
          },
          deep: true
        },
    }
2017年7月24日 15:45
編輯回答
陌如玉
require: this.requireType

你這里是將prop:‘this.requireType’當(dāng)作初始值初始化require,如果requireType的值改變的話,require是不會跟著改變的,如果不需要把requireType處理成其它數(shù)據(jù),可以直接使用它;如果要處理成其它數(shù)據(jù)給require,使用computed。

2017年2月12日 08:53