只需要记住:一个组件上的 v-model 默认会利用名为
value
的 prop 和名为input
的事件。
自定义一个custom-input组件。点击查看在线示例
<template>
<div class="custom-input">
<span>我的输入框:</span>
<input type="text" :value="value" @input="valueChanged">
</div>
</template>
<script>
export default {
props: {
value: {
type: String,
default: ""
}
},
created() {},
methods: {
valueChanged(e) {
this.$emit("input", e.target.value);
}
}
};
</script>
父组件可以直接调用:
<template>
<div>
<custom-input v-model="inputvalue"></custom-input>
<span>{{inputvalue}}</span>
</div>
</template>
<script>
import CustomInput from "./components/custom-input.vue";
export default {
name: "App",
components: {
CustomInput
},
data: function() {
return {
inputvalue: "A"
};
}
};
</script>
当custom-input
的输入框的值变化的时候,可以看到父组件的inputvalue
的值跟着变化了。
这就是自定义组件中v-model最简单的使用。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有