gpt4 book ai didi

vuejs2 - 手动实例化组件的事件处理

转载 作者:行者123 更新时间:2023-12-03 22:17:23 26 4
gpt4 key购买 nike

我正在尝试手动实例化 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com