使用手动实例化组件处理事件

时间:2018-03-18 21:13:25

标签: 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得到更新)。 当手动实例化组件时还有什么需要做的吗?

1 个答案:

答案 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)