1、标准方式:自定义输入组件
Vue.component("my-input", {
template: `
<input type="text" @input="inputHandle" :value="value">
`,
props: ["value"],
methods: {
inputHandle: function (e) {
this.$emit("input", e.target.value);
},
},
});
//使用
<my-input v-model="word"></my-input>
或者
<my-input :value="word" @input="word=$event"></my-input>
2、通过update:value实现子组件向父组件传值来实现双向绑定。可以直接使用v-bind.sync="包含属性的对象"的形式双向绑定多个属性
Vue.component("my-input", {
template: `
<input type="text" @input="inputHandle" :value="value">
`,
props: ["value"],
methods: {
inputHandle: function (e) {
this.$emit("update:value", e.target.value);
},
},
});
//使用
<my-input v-bind:value.sync="word"></my-input>
或者
<my-input v-bind:value="word" @update:value="word=$event"></my-input>