2017-07-13 30 views
0

Vue在這裏作爲測試運行的基本實現非常基礎,而且我有一些問題將數據分解爲組件。這裏是HTML:Vue組件找不到支柱

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

我實例化一個Vue的實例,並將其綁到#主標題:

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工作。

+2

您需要將屬性傳遞給模板中的組件:''這是[docs on props](https://vuejs.org /v2/guide/components.html#Props) – thanksd

+0

@thanksd這似乎適用於一些基本屬性。如何訪問像「run」這樣的父級方法?我遇到了「事件無效處理程序」的錯誤。單擊「:undefined」。 –

+1

要麼將​​它作爲道具傳遞,要麼在子組件的作用域中定義'run'方法。 [這裏是關於組件的文檔](https://vuejs.org/v2/guide/components.html)。 – thanksd

回答

1

對於需要在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>

您可以通過閱讀this document頁面獲取更多信息。

快樂編碼!