VueJS子代父代隐藏组件的布尔值。

问题描述 投票:1回答:1

大家好,感谢大家的帮助:)

上下文。在我的子代中,我想传递一个布尔值给父代,以便在用户点击父代中的组件时,隐藏该组件。

在我的子组件中( 名称 : connexionDesktop ) :

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

data () {
  return { 
    childMessage: true
  }
}

在父体中,我尝试着......但这是行不通的......我想我是个新手 :D 我不能从子体向父体发送消息^^"

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


data () {
    fromChild:false
}


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

但这是行不通的......我想我是个新手:D 我不能从子代向父代发送消息^^""

你能帮我吗?

javascript vuejs2 parent-child
1个回答
0
投票

第一个参数是 $emit 方法应该是事件名称。所以你的代码应该像这样更好看。

// 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>

然后在父组件中,你监听事件,并将子事件的值传递给父组件的一个本地值,就像这样。

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

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

1
投票

就像上面说的那样 关于$emit的文档在这里第一个参数是自定义事件名称。

你可以这样做。

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

data () {
  return { 
    childMessage: true
  }
}

而在父级事件中,

<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
    }
}

...

© www.soinside.com 2019 - 2024. All rights reserved.