【问题标题】:Parent / Child components VUE.JS 2.1.6 data passing父/子组件 VUE.JS 2.1.6 数据传递
【发布时间】:2017-01-27 12:09:54
【问题描述】:

我很困惑如何正确地将组件绑定在一起。 我在全球注册了两个组件:

Vue.component('product-welcome-component', {
    template: '#product-welcome-template',
    props: ['showModal'],
    onCreate(){
        showModal = false;
    } 

});

Vue.component('product-create-modal-component', {
    template: '#create-modal-template'   
});

在父模板中,我包含了这样的子组件:

<template id="product-welcome-template">
<div class="welcome-wrapper">
    <div class="purpose-title"><h1 class="welcome-text">Welcome to Product Hub</h1></div>
    <div class="purpose-create-btn"><button  @@click="showModal = true" class="btn btn-primary btn-success create-btn">Create New Product</button></div>
<product-create-modal-component v-if="showModal"></product-create-modal-component>
</div>
 </template>

问题是(其中一个)是我的 create-modal-component 总是显示,无论 showModal 的值如何,实际上我可以输入 v-if="1 === 2" 它仍然会显示。

我确定这不是注册父/子组件的正确方法,但我似乎找不到合适的示例。大多数情况下,我看到父级是应用程序实例,它有一个“子”组件的子级,然后它们可以通信。

我觉得在父模板中包含子组件是不好的做法,因为它会使父组件强耦合。

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 在父模板中包含子组件是什么意思?
  • 我的意思是这样的父模板:

标签: javascript components vuejs2


【解决方案1】:

您将showModal 作为product-welcome-component 的道具,但您试图在创建时将其设置为false,但您必须在created 中使用this 才能访问showModal,如下所示:

Vue.component('product-welcome-component', {
    template: '#product-welcome-template',
    props: ['showModal'],
    onCreate(){
        this.showModal = false;
    } 

});

但是你说product-create-modal-component 显示即使你做v-if="1 === 2",不应该是这种情况你能创造一个你的情况的小提琴吗?

【讨论】:

  • 一旦我重新开始工作,我会这样做,我现在设法通过让组件只与 vue 实例通信来解决我的问题,但我真的希望它们能够在它们之间进行通信通过事件和道具彼此。该文档在网站上不是很有帮助。
猜你喜欢
  • 2017-06-10
  • 2017-01-05
  • 2016-12-13
  • 2021-12-24
  • 2018-08-15
  • 2020-11-01
  • 2020-01-16
  • 2020-07-23
  • 1970-01-01
相关资源
最近更新 更多