2017-07-24 54 views
1

我現在有三個步驟需要依次顯示,因此我創建了三個組件 - 每個步驟都有一個組件。如何用組件定義屬性?

我app.js文件:

import LocationList from './components/LocationList.vue'; 
import ChooseTime from './components/ChooseTime.vue'; 
import ChooseMethod from './components/ChooseMethod.vue'; 

Vue.component('location-list', LocationList); 
Vue.component('choose-time', ChooseTime); 
Vue.component('choose-method', ChooseMethod); 

let store = { 
    isVisible: { 
     steps: { 
      one: true, 
      two: false, 
      three: false, 
     } 
    } 
}; 

new Vue({ 
    el: '#app-order', 

    data: store, 

    router 
}); 

現在,當我的唯一途徑是所謂的,從「VUE-路由器

進口VueRouter;

let routes = [ 
    { 
     path: '/order', 
     component: require('./views/Order.vue') 
    } 
]; 

export default new VueRouter({ 
    routes 
}); 

所有這些組件都正確加載。問題是,當我嘗試v-show逐一時間:

Order.vue:

<template> 

    // ... 

    <location-list v-show="isVisible.steps.one"></location-list> 
    <choose-time v-show="isVisible.steps.two"></choose-time> 
    <choose-method v-show="isVisible.steps.three"></choose-method> 

    // ... 

</template> 

<script> 
</script> 

<style> 
</style> 

我收到的錯誤消息是:

[Vue warn]: Property or method "isVisible" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. 

但是當我檢查中Vue公司的瀏覽器擴展,isVisible是在根元素中定義的?

error

正如你可以看到它是根元素,但沒有訂單視圖中雖然。

感謝您的幫助!

+0

在步驟組件模板之一中引用'isVisible'嗎? – Bert

+0

不,我只是有一個基本的文件結構像''。我沒有在其中的任何地方引用'isVisible' – Chris

+0

到目前爲止,我沒有看到有什麼問題。 – Bert

回答

1

在Vue中,子組件不能直接訪問其父項中定義的數據。你必須傳遞數據。

我認爲如果您只在Order.vue中定義了isVisible,您可能會爲自己節省一點麻煩。但是,如果您想將其保留在原來的位置,則需要將其傳遞到組件。

一個簡單的方法是將isVisble定義爲Order.vue的屬性,然後通過您的router-view傳遞它。

<router-view :is-visible="isVisible"></router-view> 

還有其他的方式將道具傳遞給defined in the router documentation

之所以我說你會救自己一些在Order.vue中定義isVisible的麻煩是因爲無論何時你想改變你的步驟的值,你都需要在根目錄下執行它,因爲你現在已經定義了它。

+0

我同意,我覺得我更喜歡在組件中定義它。我只是將isVisible對象移動到Order.vue並將其放在mounted()方法中? – Chris

+1

@Chris只是在組件數據中定義它。 'data(){return {isVisible:...}}' – Bert

+0

非常感謝Bert! – Chris