在vue-grid-layout项目内传递组件

时间:2019-02-07 20:31:24

标签: vue.js vuejs2 vue-component

请帮助我了解如何在vue-grid-layout项内传递导入的单个文件vue组件。

我知道如何传递简单的html,例如: https://jsfiddle.net/gmsa/jw2mmmpq/1/ 但是我需要用按钮和axios调用等插入其他组件

HTML:

<template>
  <div class="hello">
    <grid-layout
            :layout="layout"
            :col-num="12"
            :row-height="30"
            :is-draggable="true"
            :is-resizable="true"
            :vertical-compact="true"
            :margin="[10, 10]"
            :use-css-transforms="true"
    >

      <grid-item v-for="item in layout"
                 :x="item.x"
                 :y="item.y"
                 :w="item.w"
                 :h="item.h"
                 :i="item.i">
        <div v-html="item.c">
        </div>
        <Test></Test>
      </grid-item>
    </grid-layout>
  </div>
</template>

JS:

import VueGridLayout from 'vue-grid-layout';
  import Test from './test.vue';
  import Test from './test2.vue';

  let a = `This needs to be another component, like Test`;
  let b = `This needs to be another component, like Test2`;

  var testLayout = [
    {"x":0,"y":0,"w":2,"h":2,"i":"0", "c": a},
    {"x":2,"y":0,"w":2,"h":4,"i":"1", "c": b}
  ];
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    Test,
    Test2
  },
  data: function (){
    return {
      layout: testLayout
    }
  }
}

在这里找不到任何想法:

https://github.com/jbaysolutions/vue-grid-layout

1 个答案:

答案 0 :(得分:0)

您需要dynamic components,可以使用<component :is="component"></component>语法完成。如果您希望显示的所有项目都是组件,则可以执行以下操作:

<grid-item v-for="item in layout"
             :x="item.x"
             :y="item.y"
             :w="item.w"
             :h="item.h"
             :i="item.i">
  <component :is="item.c"></component>
</grid-item>

和JavaScript:

import VueGridLayout from 'vue-grid-layout';
import Test from './test.vue';
import Test2 from './test2.vue';
export default {
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    Test,
    Test2
  },
  data: function (){
    return {
      layout: [
        {"x":0,"y":0,"w":2,"h":2,"i":"0", "c": 'Test'}, // component name used but you could also use a reference to the component
        {"x":2,"y":0,"w":2,"h":4,"i":"1", "c": 'Test2'}
      ];
    }
  }
}

如果只有一些项目是组件,而有些则是纯HTML,则可以标记布局数组中的哪些组件:

layout: [
        {"x":0,"y":0,"w":2,"h":2,"i":"0", "c": 'Test', isComponent: true},
        {"x":2,"y":0,"w":2,"h":4,"i":"1", "c": '<h1>Hello World</h1>', isComponent: false}
      ];

然后在网格项目位置有条件地呈现组件或纯HTML。

<grid-item v-for="item in layout"
             :x="item.x"
             :y="item.y"
             :w="item.w"
             :h="item.h"
             :i="item.i">
  <template>
    <component v-if="item.isComponent" :is="item.c"></component>
    <div v-else v-html="item.c"></div>
  </template>
</grid-item>