簡體   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