首页 文章

vue.js在使用TypeScript和vue-property-decorator时如何将属性绑定到方法返回值?

提问于
浏览
2

我有一个用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-icon img标签没有src,并且 order-item-amount span缺少 / 之前的第一部分 .

对于将属性绑定到组件方法,我应该做些什么吗?

1 回答

  • 1

    当使用 Emit 进行修饰时,方法的返回值为used to determine if the event should be emitted or not .

    换句话说,用 Emit will always return undefined装饰的方法 .

    Solution: 删除装饰器并手动发出事件 .

    等效代码是:

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

相关问题