Home > front end >  Vue.js radio button no reactive
Vue.js radio button no reactive

Time:12-01

I am trying to pass the radio button value to its parent here is the example:

Child

<template>
  <radio v-model="type" value="TypeOne" @change="TypeOne()"></el-radio>
  <radio v-model="type" value="TypeTwo" @change="TypeTwo()"></el-radio>
</template>

<script>     
 export default {
  methods: {
      TypeOne() {
        this.$emit('input', 'TypeOne');
      },
      TypeTwo() {
        this.$emit('input', 'TypeTwo');
      }
    }
 }
</script>

parent

<template>
 <component @input="onTypeChange"></component>
 <div v-show="type"></div>
 <div v-show="!type"></div>
</template>

<script>
 export default {
   data() {
     return {
       type: 'true',
     };
   },
   methods: {
    onTypeChange () {
      var TypeOne = false
      var TypeTwo = false
      if (TypeOne == TypeOne) {
        this.type = false;
      } else if (TypeTwo == TypeTwo) {
        this.type = true;
      } else {
          console.log('typeChanged');
          return false;
      }
    }
  }
 }
</script>

I am trying to use radio data to hide or show some element in the parent component. in initial selection it works but after radio selection is changed it does not update the parent. How can I make the radio data reactive in my case?

CodePudding user response:

You passed a parameter when you called this.$emit('input', 'TypeOne'); but the method emitted is not accepting a parameter.

Add a parameter on onTypeChange() and use the parameter on your logic

onTypeChange (type) {
  if (type == 'TypeOne') {
    this.type = false;
  } else if (type == 'TypeTwo') {
    this.type = true;
  } else {
    console.log('typeChanged');
    return false;
  }
}
  • Related