使用Vue从JavaScript文件调用REST API
P粉170858678
P粉170858678 2023-08-29 19:23:56
[Vue.js讨论组]
<p>我有一个在Vue页面上完美运行的Axios API调用。我需要将其变成一个独立的可调用模块,以便在应用程序中多次重复使用。每次尝试都失败了,我不确定是缺乏对独立js的经验还是其他原因。</p> <p>这是可工作的Vue代码。</p> <pre class="lang-html prettyprint-override"><code>&lt;template&gt; &lt;div&gt; &lt;ul v-if=&quot;posts &amp;&amp; posts.length&quot;&gt; &lt;li v-for=&quot;post of posts&quot;&gt; &lt;p&gt;&lt;strong&gt;{{post.resID}}&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;{{post.Name}}&lt;/p&gt; &lt;/li&gt; &lt;/ul&gt; &lt;ul v-if=&quot;errors &amp;&amp; errors.length&quot;&gt; &lt;li v-for=&quot;error of errors&quot;&gt; {{error.message}} &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/template&gt; &lt;script&gt; import axios from 'axios'; export default { name: &quot;GetMxList&quot;, data() { return { posts: [], errors: [] } }, // 在组件创建时获取帖子。 created() { axios.get(&quot;http://localhost:8080/rest/...&quot;) .then(response =&gt; { // JSON响应会自动解析。 this.posts = response.data }) .catch(e =&gt; { this.errors.push(e) }) } } &lt;/script&gt; </code></pre> <p>Vue 3。谢谢你的回答。抱歉我没有表达清楚。我的目标是创建一个模块(类似于rest.js),然后在Pinia中使用它。目的是加载一次,然后经常使用结果。目前,它可以通过类似以下代码的“静态”加载工作,其中getJSONList调用返回一个JSON格式的答案,并将该答案放入MyList中以供整个应用程序使用。因此,组件只需使用Pinia映射。</p> <pre class="brush:php;toolbar:false;">actions: { async fetchList() { const data = await getJSONList(); this.Mylist = data; },</pre> <p>很多次迭代。虽然这不返回任何内容,但至少不会抛出任何错误...</p> <pre class="brush:php;toolbar:false;">import axios from 'axios'; export function getJSONList() { const rest = axios.create({ baseURL: &quot;http://localhost:8080/rest/&quot;, // 更好的做法是使用环境变量 }); const getPosts = async () =&gt; { try { return (await rest.get(&quot;http://localhost:8080/rest/&quot;)).data; } catch (err) { console.error(err.toJSON()); throw new Error(err.message); } }; return (getPosts); }</pre></p>
P粉170858678
P粉170858678

全部回复(1)
P粉464208937

通常,你只需要将Axios部分移入一个模块,并将数据的使用留给你的组件。

// services/rest.js
import axios from "axios";

const rest = axios.create({
  // 更好的方式是使用环境变量来定义你的URL
  baseURL: "http://localhost:8080/rest/tctresidents/v1",
});

// 这是一个函数
export const getResidents = async () => {
  try {
    // 请求路径将会附加到baseURL后面
    return (await rest.get("/Residents")).data;
  } catch (err) {
    // 参考 https://axios-http.com/docs/handling_errors
    console.error(err.toJSON());

    throw new Error(err.message);
  }
};

然后在你的组件/存储/任何地方...

import { getResidents } from "./path/to/services/rest";

export default {
  data: () => ({ residents: [], errors: [] }),
  async created() {
    try {
      this.residents = await getResidents();
    } catch (err) {
      this.errors.push(err);
    }
  },
};
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号