Vue.js将组件数据值传递给子组件

时间:2017-06-12 16:41:51

标签: javascript vue.js vuejs2 vue-component

我有一个组件TopBar.vue,我试图打开一个模态(子组件Feedback.vue)。

如何在两个组件之间绑定showFeedbackModal属性?

我想这样做,以便当您点击<a>标记@click="showFeedbackModal = true时,值true会传递给<feedback>组件并显示模式。< / p>

TopBar.vue(主要)

<template>
    <div>
        <section class="top-bar level">
            <div class="level-left">
                ...

                <ul class="level-item">
                    <li><a @click="showFeedbackModal = true"><i class="fa fa-envelope-open-o" aria-hidden="true"></i> Beta Feedback</a></li>
                </ul>
            </div>
            ...           
        </section> 

        <feedback :showFeedbackModal="showFeedbackModal"></feedback>            
    </div>
</template>

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

Feedback.vue(模态)

<template>
    <div>
        <div v-if="showModal" class="modal is-active">
            <div class="modal-background" @click="showModal = false"></div>
            <div class="modal-content">
                <div class="box">
                    This is the feedback content
                </div>
            </div>
            <button class="modal-close" @click="showModal = false"></button>
        </div>
    </div>
</template>

<script>
    export default {        
        props: ['showFeedbackModal'],

        data() {
            return {
                showModal: false
            }
        },

        beforeMount() {
            this.showModal = this.showFeedbackModal;
        }
    }
</script>

1 个答案:

答案 0 :(得分:3)

You are setting your showModal property in the Feedback component's mounted hook. This means that when the component is mounted to the DOM, the value of showModal will be set to whatever showFeedbackModal is initially but then won't change if the value of showFeedbackModal ever changes.

You should just make showModal a prop in your Feedback component:

export default {        
    props: ['showModal'],
}

And then, in your TopBar component, you just need to pass the showFeedbackModal variable as the value for the showModal property:

<feedback :showModal="showFeedbackModal"></feedback> 

If you want the Feedback modal component to be able to affect its parent component's showFeedbackModal variable, you can emit a custom event in the Feedback component:

<button class="modal-close" @click="$emit('close')"></button>

And then update the value of showFeedbackModal in the handler for that event:

<feedback 
  :showModal="showFeedbackModal" 
  @close="showFeedbackModal = false"
></feedback>