在vuex中提交组件

时间:2017-09-16 12:50:00

标签: vuejs2 vuex

我的vue应用程序有一个侧边栏,我想显示一个组件作为其子项。

我试图通过使用vuex商店提交它来传递组件,但它似乎无法正常工作。

我正在使用<div v-if="rightPanelOpen" class="right-panel" v-html="rightPanelComponent"></div> 来测试侧边栏组件是否可以显示子组件。

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
    }
  },

计算属性(rightPanelComponent):

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

},

我以这种方式提交子组件,

membershipFee

在这种情况下,如何在侧栏中显示子组件?

2 个答案:

答案 0 :(得分:1)

Vue动态组件使用 属性的组件元素。
请注意绑定语法(:is =&#34; ...&#34;)。

<强> 侧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中声明所有组件选择:

<强> 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' )

答案 1 :(得分:0)

v-html是一个预处理的指令!文档说:

  

请注意,内容以纯HTML格式插入 - 它们不会编译为Vue模板。如果您发现自己尝试使用v-html编写模板,请尝试使用组件重新考虑解决方案。 (https://vuejs.org/v2/api/#v-html)。

我的建议是你创建一个组件(https://vuejs.org/v2/guide/components.html)并将其插入你的rightPanelContent。可以使用props(https://vuejs.org/v2/guide/components.html#Props)传递/控制此组件的内容。