为什么我这个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();
    },
  };
阅读 9.8k
2 个回答

对于原始类型变量,watch可以直接监听,对于引用类型变量,采用深度监听。


    watch: {
        require: {
          handler: function ( newVal, oldVal ) {
              this.search();
          },
          deep: true
        },
    }
require: this.requireType

你这里是将prop:‘this.requireType’当作初始值初始化require,如果requireType的值改变的话,require是不会跟着改变的,如果不需要把requireType处理成其它数据,可以直接使用它;如果要处理成其它数据给require,使用computed。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题