子组件数据发生变化时 通过change反射给父组件
该场景在多数第三方ui库都有看到
当然实现方式有多种方式 本文采取主流的 change 事件反射
element-ui 一个input组件中
直接上代码
父组件
<template>
<div>
<children @change="getChange"></children>
</div>
</template>
<script>
import children from "./children"
export default {
components: {
children
},
methods: {
getChange(newVal,oldVal){
console.log(newVal, oldVal)
}
}
}
</script>
子组件
<template>
<div style="padding:100px">
<a-input @change="handlerChanges" v-model="value" style="width:200px" placeholder="我是子组件"></a-input>
</div>
</template>
<script>
import {Input} from "ant-design-vue"
export default {
components: {
aInput: Input
},
data(){
return {
value: ""
}
},
methods: {
handlerChanges(){
// 这里用 watch 监听 value 的变化也行
// change 是可以传递两个参数的 一个新值 一个旧值 所以可以放在watch 中一块传递
// this.$emit("change", this.value, 1)
}
},
watch:{
value(newVal, oldVal){
this.$emit("change", newVal, oldVal)
}
}
}
</script>