2017-09-16 56 views
0

我的vue應用程序有一個側欄,我想顯示一個組件作爲它的子。在vuex中提交組件

我想通過使用vuex存儲提交它傳遞組件,但它似乎無法正常工作。

我使用v-html來測試側邊欄組件是否可以顯示子組件。

<div v-if="rightPanelOpen" class="right-panel" v-html="rightPanelComponent"></div> 

計算財產(rightPanelComponent):

rightPanelComponent() { 
    if(this.$store.state.boardRightPanel.component === false) { 
     return "<div style='display: flex; align-items: center; justify-content: center; flex-grow: 1; height: 100%;'>Nothing found.</div>" 
    } else { 
     return this.$store.state.boardRightPanel.component 
    } 
    }, 

我犯這樣的子組件,

import About from '@/components/boards/post/About' 

created() { 
    document.title = 'loading ...' 
    this.$store.commit('toggleRightPanel', true) // This will show the sidebar 
    this.$store.commit('rightPanelContent', About) // This is where i am trying to send the child component for the sidebar 

}, 

我怎麼能在這個側邊欄顯示一個子組件場景?

回答

0

v-html是一個預處理指令!該文檔說:

請注意,內容作爲純HTML插入 - 它們不會被編譯爲Vue模板。如果您發現自己試圖使用v-html編寫模板,請嘗試通過使用組件重新考慮解決方案。 (https://vuejs.org/v2/api/#v-html)。

我的建議是,您創建一個組件(https://vuejs.org/v2/guide/components.html)並將其插入到您的rightPanelContent中。此組件的內容可以使用道具傳遞/控制(https://vuejs.org/v2/guide/components.html#Props)。

1

Vue動態組件使用組件元素與屬性。
請注意綁定語法(:is =「...」)。

側panel.vue

<template> 
    <component v-if="rightPanelComponent" :is="rightPanelComponent"></component> 
    <div v-if="!rightPanelComponent" style='...'>Nothing found</div> 
</template> 

computed { 
    rightPanelComponent() { 
    return this.$store.state.boardRightPanel.componentTag 
    } 
} 

簡單的是聲明所有組分的選擇在主:

main.js

import About from '@/components/About.vue 
import Another from '@/components/Another.vue 

Vue.component('my-about', About) 
Vue.component('my-another', Another) 

但你可以在側面板局部聲明所有可能的子組件:

側panel.vue

import About from '@/components/About.vue 
import Another from '@/components/Another.vue 

components: { 
    'my-about': About, 
    'my-another': Another 
} 

Parent.vue

// Set the side-panel component here by storing the tag 
this.$store.commit('rightPanelContent', 'my-about')