【问题标题】:How can I bind directives to custom components in VueJS?如何将指令绑定到 VueJS 中的自定义组件?
【发布时间】:2017-07-09 08:34:29
【问题描述】:

所以我将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>

现在一切正常,但如果我想让网格大小动态化怎么办?例如,我用类似的东西做

&lt;two-column field="Some Field" value="Some Value" sizes="xl3 md3 xs12"&gt;&lt;/two-column&gt;

这可能吗?提前谢谢你。

【问题讨论】:

  • 你能把你的例子放在JSFiddle中

标签: vue.js vuejs2 vue-component vuetify.js


【解决方案1】:

这个怎么样:

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

【讨论】:

  • 效果很好。谢谢!
【解决方案2】:

我能够做到这一点的一种方法是使用计算属性。

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

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}} 以查看正在呈现的内容。

【讨论】:

    猜你喜欢
    • 2014-12-19
    • 2019-10-29
    • 2016-11-02
    • 2018-08-22
    • 2016-04-04
    • 2012-12-14
    • 2019-04-17
    • 2021-01-03
    • 2016-11-24
    相关资源
    最近更新 更多