Implementing a v-model through a rendering function is not reactive

I am trying to create a dynamic input component that will be interchangeable between the input tag and textarea. I am trying to implement this using the render function. ( https://vuejs.org/v2/guide/render-function.html#v-model ).

The problem is that the v-model works in only one way, if I change the data property directly, it updates the textarea value, but if I change or enter new data in textarea, it does not update the data property. Does anyone know how to make it work in both directions? Here is my code link for a code pen, this illustrates the problem:

const tag = Vue.component('dynamic-tag', { name: 'dynamic-tag', render(createElement) { return createElement( this.tag, { domProps: { value: this.value }, on: { input: event => { this.value = event.target.value } } }, this.$slots.default ) }, props: { tag: { type: String, required: true } } }) const app = new Vue({ el: '#app', data: { message: '' }, components: {tag} }) 

http://codepen.io/asolopovas/pen/OpWVxa?editors=1011

+5
source share
2 answers

You need $emit to make changes from your input.

 on: { input: event => { this.value = event.target.value this.$emit('input', event.target.value) } } 
+3
source

The problem is that you are using a v-model with a custom component. When used with the v-model="message" component, only syntactic sugar is used for

 v-bind:value="message" v-on:input="value => { message = value }" 

So, in order to use the v-model with a custom component, your component must have a value prop and emit an input event with a modified value.

I will leave additional explanations to the documentation

+1
source

Source: https://habr.com/ru/post/1265192/


All Articles