简体   繁体   中英

VueJS: Sending data value from child component to parent

I have a Vue compoment rendering inside index.vue

In index.vue we have some data :

data(){
      return {
      splashIsActive: true,
      tutorialIsActive: false,
      gameIsActive: false
      }
    }

and the component inside index.vue :

<SplashBox v-if="splashIsActive"/>

Then, if we go to splashBox there's a button.

<button @click="debug">....

Is there any way to create a method that after clicking the button sends, or changes splashIsActive to false , instead of true as it is stored in index.vue?

You need to emit an event to the parent.

<button @click="debug">....


methods: {
   debug() {
     this.$emit('setSplashUnActive', false)
   }
}

In the parent component.

<SplashBox v-if="splashIsActive" @setSplashUnActive="setSplashUnActive" />


methods: {
   setSplashUnActive(value) {
      this.splashIsActive = value
   }
}

You can achieve this by emitting an event from the button .

<button @click="$emit('updateSplashState', false)">...</button>

Then, You can capture this event in parent component.

<SplashBox v-if="splashIsActive" @updateSplashState="splashIsActive = $event"/>

Live Demo :

 Vue.component('splashbox', { template: `<button @click="$emit('update-splash-state', false)">Update</button>` }); var app = new Vue({ el: '#app', data: { splashIsActive: true } });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <SplashBox v-if="splashIsActive" @update-splash-state="splashIsActive = $event"></SplashBox> </div>

You can use a prop to pass the value from parent to child. Within the child component on pressing the key you can emit an event to update its value. To do this it is necessary to indicate the prop as sync:

<SplashBox: splashUnActive.sync="initValue"></Checkbox>

and then inside SplashBox on click of the button:

this.$emit('update:splashUnActive.', newValue)

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