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"

原文地址:https://www.cnblogs.com/cnlihao/p/14109970.html