使用vite搭建vue3項目(四) 安裝axios


1.安裝axios

npm install axios

 2.修改App.vue

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
</template>

<script lang="ts">
import { defineComponent, onMounted } from "vue";
import axios from "axios"

export default defineComponent({
  name: 'App',
  setup() {
    let weather = {}
    onMounted(()=>{
      axios.get(`http://www.weather.com.cn/data/sk/101010100.html`).then(res=>{
        weather = res
      }).catch(err=>{
        console.log(err)
      })
    })

    return { weather}
  }
})
</script>

由於跨域的原因,實際請求不到數據。所以來到下一步,配置跨域代理

3.跨域代理

 配置vite.config.ts,見server部分

import {defineConfig} from 'vite'
import vue from '@vitejs/plugin-vue'
import {viteMockServe} from "vite-plugin-mock";
import path from 'path' // 需安裝此模塊


// https://vitejs.dev/config/
export default defineConfig({
plugins: [
vue(),
viteMockServe({
supportTs: true
})
],
resolve: {
alias: {
'@': path.resolve(__dirname, 'src')
}
},
server: {
host: '0.0.0.0',
port: 9000,
proxy: {
'/weatherApi': {
target: 'http://www.weather.com.cn', //實際請求地址
changeOrigin: true,
rewrite: (path) => path.replace(/^\/weatherApi/, '')
},
}
}
})

將本地端口配置為9000(默認為3000)官方文檔,配置了代理 

 將原來項目中的請求地址改成以/weatherApi開頭的 

    let weather = {}
    onMounted(()=>{
      axios.get(`/weatherApi/data/sk/101010100.html`).then(res=>{
        weather = res
      }).catch(err=>{
        console.log(err)
      })
    })

查看瀏覽器網絡請求

 

 修改App.vue將請求數據顯示在頁面上

 

<template>
  <img alt="Vue logo" src="./assets/logo.png" />
  <div>
    {{weatherinfo.city}}
    {{weatherinfo.WD}}
    {{weatherinfo.WS}}
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted, nextTick ,reactive } from "vue";
import axios from "axios"

export default defineComponent({
  name: 'App',
  setup() {
    let weatherinfo = reactive({})

     onMounted(()=>{
       axios.get(`api/data/sk/101010100.html`).then(res=>{
        Object.assign( weatherinfo, res.data.weatherinfo)
        console.log('weatherinfo', weatherinfo)
      }).catch(err=>{
        console.log(err)
      })
    })

    return { weatherinfo}
  }
})
</script>

頁面顯示截圖

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM