Vue.js中如何在API链接URL中传递变量?
替换API链接中的固定值为变量值的解决方案
首先修正你代码里的变量名拼写错误:ingridient应该改为ingredient。
接下来可以通过两种方式把变量值拼接到API链接里:
方式一:ES6模板字符串(推荐)
用反引号包裹链接,通过${变量名}插入变量值,代码如下:
const ingredient = ref("chicken"); const apiUrl = `https://api.edamam.com/api/recipes/v2?type=public&q=${ingredient.value}&app_id=MY_API_ID&app_key=MY_API_KEY`;
方式二:字符串拼接
用加号连接字符串和变量值,代码如下:
const ingredient = ref("chicken"); const apiUrl = "https://api.edamam.com/api/recipes/v2?type=public&q=" + ingredient.value + "&app_id=MY_API_ID&app_key=MY_API_KEY";
注意:因为你用的是Vue的ref响应式变量,访问它的实际值需要加上.value;如果是普通的非响应式变量,直接写变量名即可。
内容的提问来源于stack exchange,提问作者mrshiam
相关产品推荐
相关产品推荐

