<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
自写
<input-my @input="changeValue" :value="name"></input-my><br />
v-model
<input-my v-model="name"></input-my><br />
{{name}}
<button @click="add">修改</button>
</div>
<script>
//子组件
Vue.component("input-my", {
props: ["value"],
template: "<input :value=value @input='change'></input>",
methods: {
change(e) {
// 获得属性的值
console.log(e.target);
// 子传父值(自定义事件)
// 子组件中的input事件是v-model
this.$emit("input", e.target.value);
},
},
});
// 父组件
let app = new Vue({
el: "#app",
data() {
return {
name: "",
};
},
methods: {
changeValue(e) {
this.name = e;
},
add() {
this.name = this.name + "add";
},
},
});
</script>
</body>
</html>
实现vue双向数据绑定v-model
最新推荐文章于 2024-06-10 22:18:41 发布