vue.js wrapping components which have v-models vue.js wrapping components which have v-models vue.js vue.js

vue.js wrapping components which have v-models


You need to forward the value prop down to the wrapped component, and forward the update event back up (see https://vuejs.org/v2/guide/components.html#Using-v-model-on-Components for more details):

<template>  <wrapped-component    :value='value'    @input="update"  /></template><script>  import wrappedComponent from 'wrapped-component'  export default {    components: { 'wrapped-component': wrappedComponent },    props: ['value'],    methods: {      update(newValue) { this.$emit('input', newValue); }    }  }</script>

Somewhere else:

<my-wrapping-component v-model='whatever'/>


I've create a mixin to simplify wrapping of a component.

You can see a sample here.

The mixin reuse the same pattern as you with "data" to pass the value and "watch" to update the value during a external change.

export default {  data: function() {    return {      dataValue: this.value    }  },  props: {    value: String  },  watch: {    value: {      immediate: true,      handler: function(newValue) {        this.dataValue = newValue      }    }  }}

But on the wraping component, you can use "attrs" and "listeners" to passthrough all attributes and listener to your child component and override what you want.

<template>  <div>    <v-text-field        v-bind="$attrs"        solo        @blur="onBlur"        v-model="dataValue"        v-on="$listeners" />  </div></template><script>import mixin from '../mixins/ComponentWrapper.js'export default {  name: 'my-v-text-field',  mixins: [mixin],  methods: {    onBlur() {      console.log('onBlur')    }  }}</script>