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

今天要说的就是利用v-model和this.$emit('input',value)实现子传父。

众所周知,v-model是给input绑定,方便对表单的双向绑定。

其实,v-model是个语法糖,具体案例如下所示。

javascript 复制代码
<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)已经实现了子传父

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

javascript 复制代码
在父组件中调用子组件
<my-component v-model="inputValue"></my-component>

子组件
watch: {
  // sonVal是子组件的一个变量值,当他变化的时候就会触发handler将新值传给父组件的inputValue
  sonVal: {
    handler (newVal, oldVal) {
      this.$emit('input', newVal)
    },
    deep: true,
  }
}
相关推荐
小小小小宇3 小时前
TS泛型笔记
前端
小小小小宇3 小时前
前端canvas手动实现复杂动画示例
前端
codingandsleeping3 小时前
重读《你不知道的JavaScript》(上)- 作用域和闭包
前端·javascript
小小小小宇4 小时前
前端PerformanceObserver使用
前端
zhangxingchao5 小时前
Flutter中的页面跳转
前端
前端风云志5 小时前
TypeScript实用类型之Omit
javascript
烛阴5 小时前
Puppeteer入门指南:掌控浏览器,开启自动化新时代
前端·javascript
全宝6 小时前
🖲️一行代码实现鼠标换肤
前端·css·html
小小小小宇6 小时前
前端模拟一个setTimeout
前端
萌萌哒草头将军6 小时前
🚀🚀🚀 不要只知道 Vite 了,可以看看 Farm ,Rust 编写的快速且一致的打包工具
前端·vue.js·react.js