Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue V-Bind to Programmatically Created Instance

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!

like image 701
weilbith Avatar asked May 30 '26 00:05

weilbith


1 Answers

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.

like image 164
weilbith Avatar answered Jun 01 '26 20:06

weilbith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!