哎`落后了落后了,Vue处理表单除了可以用v-model绑定数据,也可以在子组件上使用v-model,实现父子传值。
细想一下确实也是,v-model是:value和@input组合的语法糖。
父组件About1.vue
<template>
<div>
About1
<!-- v-model实际就是:value="text"和@input="text=$event.target.value"的语法糖,也就是实际就相当于是在父组件文件中aa1组件上绑定value属性,然后在aa1组件中使用props接收, -->
<aa1 v-model="text"></aa1>
</div>
</template>
<script>
import aa1 from "@/components/aa1.vue";
export default {
data() {
return {
text: 123
};
},
components: {
aa1
}
};
</script>
<style lang = "less" scoped>
</style>
子组件aa1.vue
<template>
<div>
{{value}}
<button @click="change">点击改变about1的值</button>
</div>
</template>
<script>
export default {
props: ["value"],
data() {
return {};
},
methods: {
change() {
// 这里的input跟v-model的@input对应,需要使用 input 发送数据,发送的数据就是被v-model中的@input接收到赋值给了value值,最后又通过props回到了子组件中
this.$emit("input", this.value + 2);
}
}
};
</script>
<style lang = "less" scoped>
</style>
拆分来看,其实就是在子组件上绑定属性value,子组件使用props接收父组件传过来的数据value。(父传子)
在子组件上也通过@input绑定了父组件中的事件,相当于是自定义input事件,在子组件中可以通过this.$emit触发在子组件上绑定的自定义事件input,传数据给父组件(子传父)