如何将指令绑定到 VueJS 中的自定义组件?

How can I bind directives to custom components in VueJS?

所以我将 vuetify 与 vue-cli 一起使用,这是我当前的组件代码:

<template>
<div>
  <v-row>
    <v-col xl3 md3 xs12>
      <strong>{{field}}</strong>
    </v-col>
    <v-col xl9 md9 xs12>
      {{value}}
    </v-col>
  </v-row>
</div>
</template>

<script>
    export default {
       data() {
           return {

           }
       },
       props: ['field', 'value']
    }
</script>

我在我的模板中这样使用它

<template>
<two-column field="Some Field" value="Some Value"></two-column>
</template>

<script>
import TwoColumnRow from './vuetify_modifications/TwoColumnRow'
...
</script>

现在一切正常,但如果我想让网格大小动态化怎么办?例如,我使用

之类的东西

<two-column field="Some Field" value="Some Value" sizes="xl3 md3 xs12"></two-column>

这可能吗?提前谢谢你。

我能够完成此任务的一种方法是使用计算属性。

为了创建示例的简单性,我使用颜色来表示正在发生的事情。由于您真正想问的似乎是如何在组件内动态应用 类 或基于值的条件,因此这应该可以进行一些调整。

const TwoColumnRow = Vue.component('two-column', {
  template: '#two-column-row-template',
  data: function() {
    return {}
  },
  props: ['field', 'value', 'colors'],
  computed: {
    colorList: function() {
      // Split the string of colors by space and return an array of values
      return this.colors.split(' ');
    }
  }
});

const vm = new Vue({
  el: '#app-container',
  data: {}
});
.red {
  color: red;
}

.blue {
  color: blue;
}
<script src="https://unpkg.com/vue@2.1.10/dist/vue.js"></script>
<div id="app-container">
  <table>
    <two-column field="toast" value="cheese" colors="blue red"></two-column>
  </table>
</div>

<script type="x-template" id="two-column-row-template">
  <tr>
    <td v-bind:class="colorList[0]">{{field}}</td>
    <td v-bind:class="colorList[1]">{{value}}</td>
  </tr>
</script>

这会运行,因此您可以在组件中插入一些语句 {{colorList}} 以查看正在呈现的内容。

这个怎么样:

<foo :sizes="{ xl3: '', md3: '', xs12: '' }"></foo>

并且:

<template>
<div>
  <v-row>
    <v-col v-bind="sizes">
      <strong>{{field}}</strong>
    </v-col>
  </v-row>
</div>
</template>

<script>
    export default {
       props: {
           sizes: { type: Object, default: () => {} }
           // ...
       }
    }
</script>