【问题标题】:Vue V-Bind to Programmatically Created InstanceVue V 绑定到以编程方式创建的实例
【发布时间】:2018-04-19 15:40:09
【问题描述】:

我跟随this instructions 以编程方式创建了一个 Vue 实例。我使用它通过用户事件在项目中动态添加组件实例。我现在的问题是,我要初始化的组件需要一个模型。我经常这样使用它:

<my-component v-model="variable"/>

但现在我在另一个组件方法部分中使用此代码 sn-p 创建此组件:

import MyComponent from '../MyComponent'

...

add () {
  const Component = Vue.extend(MyComponent)
  const instance = new Component()
  instance.$mount()
  document.getElementById('app').appendChild(instance.$el)
}

我知道在这里使用$ref 更好,但它必须在全局范围内工作,所以我不知道如何将它添加到 DOM 中。但就像旁注一样。
现在我需要给这个instance 一个v-model 绑定。我已经知道如何定义道具或插槽,但不知道如何定义模型。在官方docu 中,他们为此提到了一些东西。但老实说,我不理解它,也没有得到它的工作。
谁能告诉我如何扩展我的代码来定义这个实例的模型?像instance.$model = this.variable 这样的东西会很棒。谢谢你!

【问题讨论】:

    标签: javascript vue.js vue-component


    【解决方案1】:

    最后我找到了一些解决方法。我不知道是否有更好的解决方案,但这对我有用。

    MyComponent 使用this description 来处理v-model。由此为父组件发出change 事件。所以这个想法只是将模型变量作为属性传递,在MyComponent 中处理该变量的副本并将更改发送给父级。要捕获此更改事件,我可以向我的实例添加以下内容:

      const Component = Vue.extend(EditWindow)
      const instance = new Component({
        propsData: { content: this.variable }
      })
    
      instance.$on('change', value => {
        this.variable = value
      })
    
      instance.$mount()
      document.getElementById('app').appendChild(instance.$el)
    

    我想这与 Vue 在后台实际执行的操作非常相似(也许?)。但毕竟它有效,我很高兴。当然,如果存在这样的解决方案,我愿意接受“正确”的解决方案。

    【讨论】:

      猜你喜欢
      • 2014-05-28
      • 1970-01-01
      • 2021-12-12
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2012-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多