我尝试手动实例化Vuejs组件,但无法将其传递给其父组件。
<template>
<div>
<input :value='value' @input='updateValue($event.target.value)'>
</div>
</template>
<script>
export default {
props: ['value'],
methods: {
updateValue: function (value) {
this.$emit('input', value);
}
}
}
</script>
组件由
初始化var ComponentClass = Vue.extend(Component);
var instance = new ComponentClass({
propsData: {
value: this.modelValue
}
});
instance.$mount();
document.getElementById('app').appendChild(instance.$el)
问题是this.modelValue
不会自动更新,因为this._events
(在组件中)不包含任何侦听器。但是,当我在模板中添加组件时,它按预期工作(来自父组件的this.modelValue
得到更新)。
当手动实例化组件时还有什么需要做的吗?
答案 0 :(得分:0)
你必须听取input
事件。这是v-model
的作用。
尝试以下代码:
var ComponentClass = Vue.extend(Component);
var instance = new ComponentClass({
propsData: {
value: this.modelValue
}
});
instance.$mount();
instance.$on('input', (e) => this.modelValue = e); // <============ added this line
document.getElementById('app').appendChild(instance.$el)