繁体   English   中英

隐藏组件的 VueJS 子级到父级 boolean 值

[英]VueJS child to parent boolean value for hide component

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

上下文:在我的孩子中,如果用户单击,我想将 boolean 传递给父级,以便在父级中隐藏一个组件

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

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

data () {
  return { 
    childMessage: true
  }
}

在父母我尝试:

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


data () {
    fromChild:false
}


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

但这不起作用...我想我是个菜鸟:我无法从孩子向父母发送消息^^“”

你能帮助我吗? 非常感谢

正如$emit here 的文档中所述,第一个参数是自定义事件名称。

你可以这样做:

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

...

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

暂无
暂无

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

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