【问题标题】:Event handling with manually instantiated component手动实例化组件的事件处理
【发布时间】:2018-03-18 21:13:24
【问题描述】:

我正在尝试手动实例化一个 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 得到更新)。 手动实例化组件时还有什么需要做的吗?

【问题讨论】:

    标签: vuejs2 vue-component


    【解决方案1】:

    您必须监听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)
    

    【讨论】:

      猜你喜欢
      • 2019-03-07
      • 1970-01-01
      • 2011-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-09
      • 1970-01-01
      相关资源
      最近更新 更多