简体   繁体   English

VueJS:将数据值从子组件发送到父组件

[英]VueJS: Sending data value from child component to parent

I have a Vue compoment rendering inside index.vue我在index.vue中有一个 Vue 组件渲染

In index.vue we have some data :index.vue我们有一些数据

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

and the component inside index.vue :index.vue里面的组件

<SplashBox v-if="splashIsActive"/>

Then, if we go to splashBox there's a button.然后,如果我们 go 到 splashBox 有一个按钮。

<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?有没有办法创建一个方法,在单击按钮后发送或将 splashIsActive 更改为false ,而不是存储在 index.vue 中的 true ?

You need to emit an event to the parent.您需要向父级emit事件。

<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发出事件来实现这一点。

<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:然后单击按钮在 SplashBox 内:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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