简体   繁体   中英

It's there any way to get v-model's variable name in the parent component from a child component

For case below, when I customize a vue component of radio, I can use model option to get the v-model value which should be a string '1'.How can I get its variable name 'radio1' in the child? It's there any way?

the child component

<template>
  <input type="radio" v-model="prop" :value="value">
</template>
<script>
export default {
  model: {
    prop: "prop"
  },
  props: {
    prop: {
      default: ''
    },
    value: {
      default: ''
    }
  }
}
</script>

the parent use this component

<template>
  <div>
    <radio-component v-model="radio1" value="1"></radio-component>
    <radio-component v-model="radio1" value="2"></radio-component>
  </div>
</template>
<script>
import radioComponent from './radio'
export default {
  components: {
    radioComponent
  },
  data () {
    return {
      radio1: '1'
    }
  }
}
</script>

You can emit an event with any name you want, so in the child you can write:

<input type="radio" @input="$emit('prop', prop)" v-model="prop" :value="value">

Then in the parent you can do:

<radio-component v-model="radio1" @prop="doSomething" value="1" name="nameValue"></radio-component>
.
.
.
data(){
   return {
     nameValue: null
    }
methods: {
doSomthing(prop){
   this.nameValue = prop
}
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM