Vue 中props的函数默认值问题

props中函数默认值,如何执行当前组件的方法?

methods: {

    sayHi(){
        alert('hi');
    }
},
props: {
    keyword: {
        default: 'a'
    },
    say: {
        type: Function,
        default: this.sayHi
    }
}

无法拿到this.sayHi函数

阅读 14.6k
3 个回答

prop 会在一个组件实例创建之前进行验证,所以即使你是用工厂函数this也不指向组件实例
唯一能与methods共享function的方法是把function单独写在实例外

function sayHi() {
  alert('hi');
}

export default {
  methods: {
    sayHi,
  },
  props: {
    say: {
      type: Function,
      default: sayHi,
    },

你好好想想 this 是啥。
两个做法:

  1. 如果此 props 是 callback 性质的话,建议改为事件绑定。
  2. 或者使用计算属性包装,return this.say || this.sayHi,然后调用此计算属性。

Vue 在初始化实例对象状态的时候,prop 里的变量是最先进行取值计算的,在 methodsdata 之前,所以它拿不到这些对象里的配置属性或方法。

如其他回答所说,看看你的需求到底是怎样的,如果是希望在子组件行为发生变化时触发父组件里的自定义方法,一般都可以改成事件:

// child component
<input v-model="name" @change="valueChanged" />

export default {
  name: 'nameInput',
  data () {
    return {
      name: ''
    }
  }
  methods: {
    valueChanged() {
      this.$emit('changed', this.name)
    }
  }
}

// parent component
<nameInput @changed="say" />
export default {
  ...
  methods: {
    say (name) {
      // 不同父组件的定制化逻辑
      ...
    }
  }
}

当然也可以不用事件直接传递:

// child component
<input v-model="name" @change="changed" />

export default {
  name: 'nameInput',
  props: {
    say: {
      type: Function
    }
  },
  data () {
    return {
      name: '大侠'
    }
  },
  methods: {
    sayHi (name) {
      console.log(`Hi ${name}`)
    },
    changed () {
      this.say ? this.say(this.name) :this.sayHi(this.name) 
    }
  }
}

// parent component
<nameInput :say="say" />
export default {
  ...
  methods: {
    say (name) {
      // 不同父组件的定制化逻辑
      ...
    }
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题