简体   繁体   中英

VueJS child to parent boolean value for hide component

Hi all and thank for helping:)

Context: In my child i want pass a boolean to the parent for hidden a component in the parent if user clicked

in my child component ( name: connexionDesktop ):

<button v-on:click="$emit(childMessage)"> Start </button>

data () {
  return { 
    childMessage: true
  }
}

in the parent i try:

<connexionDesktop v-if="fromChild == false " v-on:childToParent="childMessage"> </connexionDesktop>


data () {
    fromChild:false
}


methods: {
    childMessage (value) {
       alert('from child' + value );
       this.fromChild = value
    }
}

but that's not working... i think i am a noob:D i can't send a message from child to parent ^^""

can you help me? thank a lot

As it's stated in the docs on $emit here , the first parameter is the custom event name.

You can do something like this:

<button v-on:click="$parent.$emit('childToParent', childMessage)"> Start </button>

data () {
  return { 
    childMessage: true
  }
}

and in the parent:

<connexionDesktop v-if="fromChild == false " v-on:child-to-parent="childMessage"> </connexionDesktop>

...

data () {
    fromChild:false
}


methods: {
    childMessage (value) {
        alert('from child' + value );
        this.fromChild = value
    }
}

...

The first argument for the $emit method should be the event name. So your code should look better like this:

// child component
<template>
 <button v-on:click="handleClick"> Start </button>
</template>

<script>
export default {
   data () {
     return { 
      childMessage: true
     }
   },
   methods: {
    handleClick() {
      this.$emit('update:parent', this.childMessage)
    }
  }
}


</script>

Then in the parent component, you listen for the event and pass in the value the child emitted to a local value of the parent like so:

<template>
   <connexionDesktop v-if="fromChild == false" @update:parent="fromChild = $event"> 
   </connexionDesktop>
</template>

<script>
export default {
   data () {
    return {
     fromChild: false
    }
   },
}
</script>

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