【问题标题】:Can I inject custom view components into a Vue.js grid component?我可以将自定义视图组件注入 Vue.js 网格组件吗?
【发布时间】:2016-07-28 08:04:18
【问题描述】:

我在 Vue.js 中有一个数据网格组件,看起来有点像官方示例中的那个:http://vuejs.org/examples/grid-component.html

基于输入数据而不是纯字符串,有时我想将“装饰”的条目显示为复选框或 v-link 组件(不仅如此,我可能还需要渲染其他组件,例如未转义的 HTML 或图像)。

显然我不想为所有用例准备 Grid 组件,所以这不是我想做的:

要显示的示例数据模型:

model = [
  {
    field1: 'some string',
    field2: 'another string',
    field3: { // this should be a checkbox
      state: true
    },
    field4: { // this should be an <a v-link>
      url: 'http://whatever',
      label: 'go somewhere'
    }
  }
]

Grid 组件的相关摘录:

<template>
  ...
    <tr v-for="entry in model">
      <td>
        <div v-if="typeof entry === 'object' && entry.hasOwnPropery('url')">
          <a v-link="entry.url">{{ entry.label }}</a>
        </div>
        <div v-if="typeof entry === 'object' && entry.hasOwnProperty('state')">
          <input type="checkbox" v-model="entry.state">
        </div>
        <div v-else>
          {{ entry }}
        </div>
      </td>
    </tr>
  ...
</template>

Vue.js 将自定义组件作为装饰器注入的理念是什么?我希望我的 Grid 对这些装饰器组件完全不可知。

【问题讨论】:

    标签: components decorator vue.js


    【解决方案1】:

    这将是一个可变组件的好地方。您定义了几个不同的装饰器组件,然后使用您的数据来决定应该使用哪个来进行渲染。

    模板:

    <div id="app">
    <ul>
        <li
        v-for="entry in entries"
        >
        <component :is="entry.type">
            {{ entry.content }}
        </component>
        </li>
    </ul>
    </div>
    

    组件:

    new Vue({
      el: '#app',
      components: {
        'blank': {
          template: '<div><slot></slot></div>'
        },
        'green': {
          template: '<div style="color: #0f0;"><slot></slot></div>'
        },
        'red': {
          template: '<div style="background-color: #f00;"><slot></slot></div>'
        }
      },
      computed: {
        entries: function() {
          return this.raw_entries.map(
            function(entry) {
              if (typeof entry !== "object") {
                return { type: 'blank', content: entry }
              }
    
              if (!entry.hasOwnProperty('type')) {
                entry.type = 'blank'
              }
    
              return entry
            }
          )
        }
      },
      data: {
        raw_entries: [
          'Base Text',
          {
            type: 'green',
            content: 'Green Text'
          },
          {
            type: 'red',
            content: 'Red Background'
          }
        ]
      }
    })
    

    JsFiddle 使用列表的工作示例

    【讨论】:

      猜你喜欢
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-26
      • 1970-01-01
      • 2013-02-07
      • 2019-03-21
      相关资源
      最近更新 更多