我正在尝试手动实例化 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
被更新)。当组件被手动实例化时,还有什么需要做的吗?
最佳答案
你必须听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)
关于vuejs2 - 手动实例化组件的事件处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49352856/