You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Vue组件中使用MTG SDK获取数据并正确给cardName赋值的方法

问题解决方法

你的赋值逻辑本身没有问题,核心问题是定义的getCardName方法没有被触发执行,接口请求不会自动发起,自然无法给cardName赋值。你需要在组件的生命周期钩子中调用该方法,即可完成赋值。

你可以直接使用下方修正后的代码:

<template>
    <h1>{{ cardName }}</h1>
</template>

<script>
const mtg = require('mtgsdk')

export default {
    name: 'Card',
    data: function() {
        return {
            cardName: null
        }
    },
    // 新增created生命周期钩子,组件创建完成后自动调用请求方法
    created() {
        this.getCardName()
    },
    methods: {
        getCardName() {
             mtg.card.find(3)
                .then(result => {
                    this.cardName = result.card.name // 赋值成功后页面自动渲染"Black Lotus"
                })
                // 额外补充错误捕获逻辑,避免请求失败导致页面报错
                .catch(err => {
                    console.error('卡牌信息查询失败:', err)
                    this.cardName = '暂无卡牌信息'
                })
        }
    }
}
</script>

<style>
</style>

如果偏好更易读的async/await写法,也可以把请求方法改成如下形式:

async getCardName() {
  try {
    const result = await mtg.card.find(3)
    this.cardName = result.card.name
  } catch (err) {
    console.error('卡牌信息查询失败:', err)
    this.cardName = '暂无卡牌信息'
  }
}

内容的提问来源于stack exchange,提问作者LaraC

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 17:27:05