Vue 3 使用vue-cli 4.x安裝AntD 2.x,並配置axios及使用代理解決跨域問題


1. 安裝腳手架工具

$ npm install -g @vue/cli

2. 創建一個項目

vue create antd-demo

這里腳手架會自動創建文件目錄。
Vue 3同其他版本不太一樣,是這樣的:

#main.js文件
import { createApp } from 'vue'
import App from './App.vue'

createApp(App).mount("#app");

3. 安裝AntD 2.x組件

npm i --save ant-design-vue@next

4. 完整引入AntD

import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import App from './App.vue'
import 'ant-design-vue/dist/antd.css';


const app = createApp(App);
app.config.productionTip = false;

app.use(Antd).mount("#app");

局部引入請查看官方文檔:https://2x.antdv.com/docs/vue/getting-started-cn/

5. 安裝axios

npm install axios

6. 引入axios

import { createApp } from 'vue'
import Antd from 'ant-design-vue';
import App from './App.vue'
import axios from "axios";
import 'ant-design-vue/dist/antd.css';


const app = createApp(App);
app.config.productionTip = false;
app.config.globalProperties.$axios = axios
app.use(Antd).mount("#app");

7. axios使用

一、直接全局使用【不推薦】

this.$axios.post('xxx',xxx)....

二、獲取上下文的方式使用【不推薦】

#在組件內調用http時需要使用getCurrentInstance()來獲取
const { ctx } = getCurrentInstance(); //獲取上下文實例,ctx=vue2的this
ctx.$axios.post('xxx',xxx)....

三、vue3中使用Provide/Inject依賴注入,替代vue2中在原型鏈上掛載一些屬性【推薦】

參考資料:
https://github.com/vuejs/rfcs/pull/117
https://v3.vuejs.org/guide/component-provide-inject.html
TODO:等我學習后再添加

8. axios配置代理,解決跨域

這個需要自己在根目錄創建配置文件:vue.config.js

然后,里面添加:

module.exports = {
    publicPath: './',
    devServer: {
        // 設置代理
        proxy: {
            '/api': {
                target: 'http://localhost:9527',//此處可以換成自己需要的地址
                changeOrigin: true,
                pathRewrite: {
                    '^/api': '/api'
                }

            }
        }
    }
}

關於報錯:

vue引入導航守衛報錯error: 'APP' is defined but never used (no-unused-vars)

報錯原因: 該項目安裝了eslint規范,ESLint 是在 ECMAScript/JavaScript 代碼中識別和報告模式匹配的工具,它的目標是保證代碼的一致性和避免錯誤。在許多方面,它和 JSLint、JSHint 相似。

解決方法1:

在package.json文件內加入如下代碼:保存后重啟項目!

"rules": {
      "generator-star-spacing": "off",
      "no-tabs":"off",
      "no-unused-vars":"off",
      "no-console":"off",
      "no-irregular-whitespace":"off",
      "no-debugger": "off"
    }

解決方法2:
在安裝項目的時候不安裝ESLint:

Use ESLint to lint your code? NO

以上引用自 FivePointOne 的文章,地址:https://www.cnblogs.com/FivePointOne/p/13889709.html

關於代理不生效

問題原因:有可能是nodejs代理服務器沒有及時重啟。
問題解決:
添加:

    "start": "node index.js",
    "server": "nodemon index.js --ignore client"


免責聲明!

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



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