【问题标题】:Vue JS does renders braces instead of resultVue JS 会渲染大括号而不是结果
【发布时间】:2017-05-26 07:44:59
【问题描述】:

我正在使用 Vue JS (2.0.8) 来呈现设备列表。我有一个由数字表示的健康状态,所以我使用一种方法将数字转换为 CSS 类以正确显示它。问题是vue渲染的不是方法的结果,而是方法调用本身。

我的 Vue 方法:

methods: {
    ...
    health: function (device) {
        if (device !== null) {
            switch (device.health.status) {
                case 2:
                    return "connected";
                    break;
                case 1:
                    return "warning";
                    break;
                case 0:
                    return "disconnected";
                    break;
                case -1:
                default:
                    return "unsupported";
                    break;
            }
        }
    },
    ...
}

我的 HTML(我使用 Laravel,因此使用了“@”):

<div v-for="device in devices" class="device">
    <div class="device-top">
        <div class="device-bullet @{{ health(device) }}"></div>
        <div v-on:click="device.open = !device.open" v-bind:class="{open: device.open}" class="device-more-info"><span class="icon icon-show-more"></span>More info</div>
    </div>
</div>

这会呈现以下 HTML:

<div class="device>
    <div class="device-top">
        <div class="device-bullet {{ health(device) }}"></div>
        <div class="device-more-info"><span class="icon icon-show-more"></span>More info</div>
    </div>
</div>

然而,这有点奇怪。如果我将 @{{ health(device) 移动到 device-bullet div 内部而不是在属性中使用它,它会呈现如下(正确地,“连接”是函数的结果)。

<div class="device>
    <div class="device-top">
        <div class="device-bullet">connected</div>
        <div class="device-more-info"><span class="icon icon-show-more"></span>More info</div>
    </div>
</div>

我尝试了任何我能想到的组合以使其正确渲染,但似乎找不到问题。

感谢您的帮助,提前感谢您。

【问题讨论】:

  • vuejs 2 中属性内的插值是removed

标签: javascript html laravel vue.js


【解决方案1】:

属性内插值一直是removed in Vue 2.x

改用v-bind:class:

<div class="device-bullet" v-bind:class="[health(device)]"></div>

【讨论】:

  • +1,但您也许可以考虑添加 why 以确保完整性。
  • @MathewJibin 感谢您的链接。我更新了我的答案。
【解决方案2】:

不知道 laravel 是怎么工作的,以前没用过。

但在“纯”vue 中不能使用 {{}} 语法来绑定 html 属性。你需要使用v-bind指令

<div v-bind:class="'device-bullet '+ health(device)" ></div>

如果没有v-bind:,您实际上是在使用device-bullet {{ health(device) }} 作为值。 如需更多说明,请查看this docs section

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 2016-12-16
    • 2021-04-09
    • 2019-12-06
    相关资源
    最近更新 更多