【问题标题】:Calling component method in template while v-foring the componentv-foring 组件时在模板中调用组件方法
【发布时间】:2018-03-07 18:35:45
【问题描述】:

我正在使用 vuejs2。我想在我的组件中创建一个方法,然后调用它来将一个类绑定到它,但我无法让它工作。这是我或多或少想要完成的事情,getMachineClass() 理想情况下将是我的机器组件中的一个方法。

<machine
      v-for="item in machinesList"
      v-bind:key="item.id"
      v-bind:machine="item"
      v-bind:class="item.getMachineClass()">
</machine>

我知道我可以将方法放在我的 vue 实例中,然后像这样调用它:

v-bind:class="getMachineClass(item)

我希望该方法仅在组件中。我该怎么办?

机器组件:

Vue.component('machine', {
        props: ['machine'],
        template: '#machine',
        data: function () {
            return {
                translations: translations,
                options: options
            }
        },
        mounted: ...
});

【问题讨论】:

  • 不知道你为什么要那样做......但是你通过使用作用域插槽使它工作......你能显示你的机器组件代码
  • 已添加。好吧,我认为这是一个好主意,因为确定类的逻辑取决于机器(所以机器列表中的项目)。
  • 我对模板很感兴趣

标签: vuejs2 vue-component


【解决方案1】:

你可以在你的机器组件的根元素上绑定class

//machine component template
<script type="text/x-template" id="machine">
    <div v-bind:class="getMachineClass(machine)">
     //...
    </div>
</script>    

由于您将迭代项目作为 machine 属性接收,请将其传递给 getMachineClass 方法

【讨论】:

    猜你喜欢
    • 2021-05-23
    • 1970-01-01
    • 2019-07-22
    • 1970-01-01
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 1970-01-01
    • 2019-04-14
    相关资源
    最近更新 更多