当前位置: 首页 > 知识库问答 >
问题:

vue。js在使用TypeScript和vue属性装饰器时,如何将属性绑定到方法返回值?

轩辕海
2023-03-14

我有一个用TypeScript编写的单文件vue组件。我在模板中使用了一些组件方法来绑定属性,但对于这些值,dom保持为空。

模板(它的一部分,为简单起见而裁剪)如下所示:

<div class="order-items">
    <div class="order-item" v-for="(item, itemIndex) in order.items">
        <img class="order-item-icon" :src="getIcon(item.name)" />
        <span class="order-item-name">{{ itemsList[item.name].name }}</span>
        <span class="order-item-amount">{{ getPlayerAmount(item.name) }}/{{ item.amount }}</span>
    </div>
</div>

在脚本部分,有这些方法。我使用的是vue property decorator,不确定这会产生多大影响:

@Emit() getPlayerAmount(itemName: string): string {
    if (this.inventory[itemName]) {
        return `'${this.inventory[itemName].amount}'`;
    } else {
        return '0';
    }
}

@Emit() getIcon(itemName: string): string {
    const icon = Items.getItemData(itemName).icon;
    return icon;
}

这些方法由我的模板调用,如上所示。我曾尝试在代码中设置断点,这些方法确实会被调用并返回正确的值。然而,dom仍然是空的。order item图标img标记没有src,并且order item amountspan缺少/前面的第一部分。

在将属性绑定到组件方法时,我应该做些什么?

共有1个答案

臧烨烁
2023-03-14

当使用Emit修饰时,该方法的返回Vue用于确定是否应该发出事件。

换句话说,用Emit修饰的方法将始终返回un定义

解决方案:移除装饰器并手动发出事件。

等效代码为:

getPlayerAmount(itemName: string): string {
    this.$emit('get-player-amount', itemName);
    if (this.inventory[itemName]) {
        return `'${this.inventory[itemName].amount}'`;
    } else {
        return '0';
    }
}

getIcon(itemName: string): string {
    const icon = Items.getItemData(itemName).icon;
    if (icon) this.$emit('get-icon', itemName);
    return icon;
}
 类似资料:
  • 我得到了这个错误 属性内的内插已被删除。改用v-bind或冒号速记。例如,代替

  • Object.defineProperty(target, key, { writable: false }); } @ReadOnly // notice there are no `()` name: string; const t = new Test(); t.name = 'jan';

  • 问题内容: 这段代码返回一个错误:AttributeError:无法设置属性这真的很遗憾,因为我想使用属性而不是调用方法。有谁知道为什么这个简单的例子不起作用? 问题答案: 这是你想要的吗? 取自http://docs.python.org/library/functions.html#property。

  • 我在这个库中使用typescript。我在文件中有以下代码: 编译完成后,在浏览器中运行,并在vue警告后chrome控制台中的输入框中键入内容: [Vue warn]:避免直接改变道具,因为每当父组件重新渲染时,该值将被覆盖。相反,使用基于道具值的数据或计算属性。道具变异:“某物名” 你知道怎么解决这个问题吗?

  • 我正在使用typecript和vue。 在我的应用程序中有一个,它对每个子组件都是全局的。 我在vue JS上找到了本机vue解决方案,将此属性注入子组件。 在main.ts 在任何typescript vue组件上 这样我就可以在我的子组件上获得注入的

  • 本文向大家介绍vue中的循环对象属性和属性值用法,包括了vue中的循环对象属性和属性值用法的使用技巧和注意事项,需要的朋友参考一下 v-for除了可以循环数组,还可以循环对象。 例子: 结果: 补充知识:Vue控制路由滚动行为 跳转路由时,要求跳转到指定路由的某个地方,可以使用scrollBehavior方法控制。 用法: scrollBehavior(to,from,savedPosition)