vue子传父的一种新方法:this.$emit(‘input‘, value)可实现实时向父组件传值

今天要说的就是利用v-model和this.$emit(‘input’,value)实现子传父。
众所周知,v-model是给input绑定,方便对表单的双向绑定。
其实,v-model是个语法糖,具体案例如下所示。

<input v-model="inputValue">

相当于
<input v-bind:value="inputValue" v-on:input="inputValue = $event.target.value">

在自定义组件中
<my-component v-model="inputValue"></my-component>

相当于
<my-component v-bind:value="inputValue" v-on:input="inputValue = argument[0]">
</my-component>

这个时候,inputValue接受的值就是input事件的回调函数的第一个参数,
所以在自定义组件中,要实现数据绑定,还需要$emit去触发input的事件。
this.$emit('input', value)//这个是在子组件中调用的
其实通过this.$emit('input', value)已经实现了子传父

我们今天所说的是自定义组件实时子传父,请继续看下面代码:

在父组件中调用子组件
<my-component v-model="inputValue"></my-component>

子组件
watch: {
  // sonVal是子组件的一个变量值,当他变化的时候就会触发handler将新值传给父组件的inputValue
  sonVal: {
    handler (newVal, oldVal) {
      this.$emit('input', newVal)
    },
    deep: true,
  }
}

你可能感兴趣的:(vue,面试,vue.js,前端,javascript)