【问题标题】:Vue3 Composition API, how to get data from service?Vue3 Composition API,如何从服务中获取数据?
【发布时间】:2021-07-08 11:03:51
【问题描述】:

我正在尝试使用 Vue3 的 Composition API。但是有些地方我找不到。相同的代码在两个不同的项目中不起作用。

我在自己的项目中想做的就是通过API来获取数据,按照需要使用。简而言之,做必要的 get/post 操作。我从 Vue 自己的示例中得到了这个 API。

这是第一个项目代码,package.json和错误信息

<template>
  <div class="home">
    <div v-for="datas in data" :key="datas.description">
      {{ datas.description }}
    </div>
  </div>
</template>

<script lang="ts">
import { Options, Vue } from "vue-class-component";
import axios from "axios";
import { ref } from "vue";

@Options({
  props: {
    msg: String,
  },
})
export default class HelloWorld extends Vue {
  setup() {
    let data = ref([]);
    axios
      .get("https://api.coindesk.com/v1/bpi/currentprice.json")
      .then((res) => {
        data.value = res.data.bpi;
      });
  }
}
</script>

{
  "name": "api-project",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "core-js": "^3.6.5",
    "vue": "^3.0.0",
    "vue-class-component": "^8.0.0-0",
    "vue-router": "^4.0.0-0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-router": "~4.5.0",
    "@vue/cli-plugin-typescript": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2",
    "typescript": "~4.1.5"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

Vue warn

这是第二个项目代码,package.json和数据

<template>
  <div v-for="datas in data" :key="datas.description">
    {{ datas.description }}
  </div>
</template>

<script lang="ts">
import axios from "axios";
import { ref } from "vue";

export default {
  name: "HelloWorld",
  setup() {
    let data = ref([]);
    axios.get("https://api.coindesk.com/v1/bpi/currentprice.json").then((res) => {
      data.value = res.data.bpi;
    });

    return {
      data,
    };
  },
}
</script>

{
  "name": "test-api",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "serve": "vue-cli-service serve",
    "build": "vue-cli-service build",
    "lint": "vue-cli-service lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "core-js": "^3.6.5",
    "vue": "^3.0.0"
  },
  "devDependencies": {
    "@vue/cli-plugin-babel": "~4.5.0",
    "@vue/cli-plugin-eslint": "~4.5.0",
    "@vue/cli-service": "~4.5.0",
    "@vue/compiler-sfc": "^3.0.0",
    "babel-eslint": "^10.1.0",
    "eslint": "^6.7.2",
    "eslint-plugin-vue": "^7.0.0",
    "node-sass": "^4.12.0",
    "sass-loader": "^8.0.2",
    "typescript": "~4.1.5"
  },
  "eslintConfig": {
    "root": true,
    "env": {
      "node": true
    },
    "extends": [
      "plugin:vue/vue3-essential",
      "eslint:recommended"
    ],
    "parserOptions": {
      "parser": "babel-eslint"
    },
    "rules": {}
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not dead"
  ]
}

my data

在我的 Composition API 使用中会出现错误吗?我听说在某些视频中,“然后”不用于合成 API。但这是我能够从 API 中提取数据的唯一方法。

如果我的解决方法不对,应该是什么方法,我是Vuejs的新手,你能帮忙吗?

【问题讨论】:

  • 您需要从setup 函数中返回变量,以便在渲染过程中使用它们。

标签: vue.js vuejs3 vue-composition-api


【解决方案1】:

您需要从setup 函数返回变量,以便可以从模板中访问它们。

如果setup返回一个对象,对象上的属性可以是 在组件的模板中访问,以及 传入设置的道具:

setup() {
    let data = ref([]);
    axios
      .get("https://api.coindesk.com/v1/bpi/currentprice.json")
      .then((res) => {
        data.value = res.data.bpi;
      });
      // return the data as an object
      return {
          data
      }
  }

在官方 vue doc了解更多信息

【讨论】:

  • 谢谢,但问题仍然存在。 console.log() 它在 setup() 中也不起作用。问题可能是我使用的“导出默认类 HelloWorld 扩展 Vue”吗?在 cmd 中,我通过自己选择属性来创建项目。
【解决方案2】:

您可以在src 文件夹中创建api 目录,然后在api 目录中创建一个文件 api.ts 并放入此代码

export async function callApi(endpoint :string, method :string){
    return await fetch(endpoint,{
        method:method,
        headers: {
                'Content-type': 'application/json; charset=UTF-8',
        },
    }).then(async response => {
        const resData = await response.json()
        if (!response.ok) {
            // do something to determine request is not okay
             resData.isSuccess = false
        }
        return resData
    }).catch(error => {
        console.log("callApi in api.ts  err")
        console.log(error)
        throw error
    })
}

转到您的组件并使用此代码

<template>
    <div  v-for="(item,i) in data.records" v-bind:key="i">
      {{ item.chartName}}
    </div>
</template>

<script>
import {onMounted,reactive} from "vue"
import {callApi} from "@/api/api"

export default{
    name:'MyComponent',
    setup() {

        const data = reactive({
            records: [],
        })

        onMounted( async() =>{
            getRecords()
        })

         const getRecords = async() => {
            let resData = await callApi('https://api.coindesk.com/v1/bpi/currentprice.json', 'GET')
            data.records = resData
        }

        return {
          data,
        }
    }
   }
</script>
enter code here

【讨论】:

  • callApi in api.ts errapi.ts?de46:16 TypeError: Failed to fetch 我收到了这些错误。我在 fetch' 标题中添加了 mode: 'no-cors'。但是我收到了这个错误Uncaught (in promise) SyntaxError: Unexpected end of input
猜你喜欢
  • 2022-06-29
  • 2021-12-11
  • 2021-04-03
  • 2021-11-30
  • 2021-11-15
  • 2022-01-23
  • 2021-03-16
  • 1970-01-01
  • 2021-06-08
相关资源
最近更新 更多