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

标签 vuejs2 vue-component

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

相关文章:

javascript - VueJS v-model 和组件之间的数据绑定(bind)

vue.js - 如何将图像 src 传递到 Vue 中的模态对话框(以便缩放单击的图像)?

javascript - VueJS 数据对象是 2 个数据对象的组合

javascript - 使用 VueJS 的 WebRTC : Why the remote video is not playing?

javascript - 将对象数组传递给 vue.js 中的组件

vue.js - 如果 prop 参数为 null,则使用默认值

Vue.js:用户单击按钮时加载模板(或 div)?

javascript - 如何从插槽中调用组件方法 - Vue

vue.js - 视觉 : Change class with the value of a variable in setInterval

vue.js - 如何在范围外更改 vue.js 组件数据