簡體   English   中英

Vue 組件找不到 Prop

[英]Vue Component Cannot Find Prop

Vue 的基本實現在這里作為測試運行,我在將數據分解為組件時遇到了一些問題。 這是HTML:

<body>
    <header id="main-header">
       <custom-header></custom-header>
    </header>
</body>

我正在實例化一個 Vue 實例並將其綁定到#main-header:

import CustomHeader from '../header.vue';

chx = {
    dates: { dateFormatted:"2016-01-01"},
    title: "Hello World",
    settingsVisible: false
} 

const header = new Vue({
    el: '#main-header',
    data: chx,
    components: {
        'custom-header': CustomHeader
    },
    methods: {
        run: function() {
            console.log('run');
        },
        print: function() {
            window.print()
        },
        save: function() {
            console.log('save');
        }
    }
});

和導入的模板:

<template>
<div>
    <div class="header-menu">
        <img class="logo" src="images/logo.png">
    </div>
    <i v-on:click="run" id="run" class="fa fa-3x fa-play-circle run-icon no-print" aria-hidden="true"></i>
    <div class="header-menu">
        <h1 id="date-range-label"><span v-show="dates.startFormatted">{{dates.startFormatted}} - {{dates.endFormatted}}</span></h1>
        <i v-on:click="settingsVisible = !settingsVisible" id="settings" class="fa fa-2x fa-cog settings-icon no-print"></i>
    </div>
</div>
</template>

<script>
    export default {
        props: ['title', 'dates']
    }
</script>

我最大的問題是我的模板無法從我創建的chx對象中找到任何數據。 我收到錯誤"TypeError: Cannot read property 'startFormatted' of undefined" 我想我可能不得不使用bind但我不確定如何與v-showv-on結合使用。

對於第一部分,您需要在header.vue組件中定義一個道具,如下所示:

props: {
    'propname': { type: Object }
}

然后傳遞您在父組件中創建的chx對象:

<custom-header :propname="chx"></custom-header>

現在您可以像這樣在子組件中訪問父級的數據:

{{ propname.dates.startFormatted }}

對於問題的第二部分,您需要觸發一個事件來通知父組件更新settingsVisible 你可以這樣解決這個問題:

<i v-on:click="toggleSettings()" id="settings" class="..."></i>
//
//
methods: {
    toggleSettings() { this.$emit('toggle'); }
}

並在父組件中監聽toggle事件:

<custom-header :propname="chx" v-on:toggle="chx.settingsVisible = !chxsettingsVisible"></custom-header>

您可以通過閱讀此文檔頁面獲取更多信息。

快樂編碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM