3

I follewed this instructions to create a Vue instance programmatically. I use this to dynamically add component instances in project by user events. My problem now it, that my component to initialize needs a model. I regular I would use it like this:

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

But now I create this component with this code snippet within another components methods section:

import MyComponent from '../MyComponent'

...

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

I know using a $ref here is better, but it must work globally, so I didn't know how to add it else to the DOM. But just as side note.
Now i need to give this instance a v-model binding. I already know how to define props or slots, but not a model. In the official docu they mention something for that. But to be honest I don't understand it and didn't get it work.
Can anybody tell me how I have to extend my code to define the model for this instance? Something like instance.$model = this.variable would be awesome. Thank u!

0

1 Answer 1

1

Finally I got some kind of workaround for this. I'm not aware if there is a better solution out there, but this works for me.

The MyComponent used this description to handle the v-model. By this is emit the change event for the parent component. So The idea is simply to pass the model variable as property, work in MyComponent on a copy of this variable and emit changes to the parent. To catch this change event I can add to my instance the following:

  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)

I guess this is pretty the same as Vue actually does in the background (maybe?). But after all it works and I'm happy. Of cause I'm open for the 'correct' solution, if such one should exist.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.