VueJs如何将prop数据作为API入参?解决props未定义报错问题
问题修复方案
核心报错原因
你遇到的ReferenceError: props is not defined报错,根本原因是Vue选项式API的methods方法中,不能直接通过props变量访问组件属性,所有声明的props、data、computed属性都会挂载到组件实例this上,需要通过this访问对应属性。
除此之外你的代码还有两个隐性问题:
- props声明格式错误,选项式API中props需要指定属性类型,不能直接赋值默认值
- DeepL翻译接口的请求格式不符合官方规范,直接传文本会导致接口调用失败
修复后的完整TranslationButton.vue代码
<template> <b-button type="is-text" @click="translateMessage()">Übersetzen</b-button> </template> <script> export default { name: "TranslationButton", // 修正props声明格式 props: { text: { type: String, default: '' } }, methods: { async translateMessage() { const url = "https://api.deepl.com/v2/translate"; const response = await fetch(url, { method: "POST", headers: { // 修正DeepL认证头格式,替换为你自己的实际密钥 "Authorization": "DeepL-Auth-Key 你的DeepL密钥", "Content-Type": "application/json" }, // 修正props访问方式、修正DeepL接口请求体格式 body: JSON.stringify({ text: [this.text], target_lang: "EN-GB" }) }); const translateRes = await response.json() // 可在此处添加后续逻辑,比如将翻译结果emit给父组件 console.log('翻译结果', translateRes) return translateRes } } }; </script>
补充说明
父组件MainComponent.vue中的组件调用写法没有问题,无需修改。
内容的提问来源于stack exchange,提问作者user16741832
相关产品推荐
相关产品推荐

