vue3+vite安装route路由、axios(跨域)

0. 安装vue3+vite:

### vue3+vite:
开发环境打包:
npm run dev
运行环境打包:
npm run build


### 构建新vite:
npm init vite-app <项目名称>
//切换到项目目录
cd <项目名称>
//安装依赖
npm install

1. 安装route依赖:

npm install vue-router@4
npm install axios --save

# 其他
npm install element-plus --save
npm i wangeditor --save
npm i swiper
npm install chart.js --save

2. 整理vue3的目录(使用默认的话就请略过):

2-1:整理index.html文件(需要重新设置main.js引用路径):

<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta name="robots" content="noindex, nofollow"/>
  <link rel="icon" href="/src/assets/favicon.ico" type="image/x-icon"/>
  <title>示例-Vue</title>
  <meta name="keywords" content=""/>
  <meta name="description" content=""/>
  <meta name="author" content="" />
  <script> // 手动,第三方统计代码位置 </script>
</head>
<body class="body" data-size="px" title="Vue3+vite">
  <div id="app"><!-- built files will be auto injected --></div>
  <script type="module" src="/src/assets/vue/main.js" title="vue入口文件"></script>
</body>
</html>

2-2.整理main.js:

将app.vue和main.js移动到文件夹/src/assets/vue/下:

vue3+vite安装route路由、axios(跨域)

2-3.设置main.js参数:

main.js完整代码如下:

import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App); // 挂载

import {config} from '../../config/config.js';
import {common} from '../../assets/es/common.js';

// 全局变量
app.config.globalProperties.config = config; // 配置文件
app.config.globalProperties.common = common; // 公共函数

// 路由
import router from "../../route/route";
app.use(router);

// axios
import axios from 'axios';
// axios.defaults.baseURL = config.api_url; // 设置了主域名则接口就不需要+了
axios.defaults.withCredentials = false; // 跨域设置,false忽略跨域cookies(Access-Control-Allow-Headers:*)
axios.defaults.timeout = 16000; // 等待时间,ms

// Element-plus UI
// 文档https://element-plus.gitee.io/#/zh-CN/component/quickstart
import ElementPlus from 'element-plus';
import 'element-plus/lib/theme-chalk/index.css';
app.use(ElementPlus, { size: 'small', zIndex: 5000 });
import {ElMessage} from 'element-plus'
app.provide('$message', ElMessage);


app.mount('#app');

app.vue代码如下,仅作参考:

<template>
  <div class="app-content">
    <router-view ref="page"></router-view>
    <div class="clear"></div>
  </div>
</template>

<script>

  export default {
    name: 'App',
    components: {},
    setup(){ // 系统创建完成
      let that = this;
      console.log("=setup");
      return {

      };
    },
    mounted() { // 组件初始化完成
      let that = this;
      console.log("=mounted");
      //console.log(that.$refs.page_must.); // 访问子组件
    },
    updated() { // 视图更新
      let that = this;
      console.log("=updated");
    },
    unmounted() {
      let that = this;
      console.log("=unmounted");
    },
    methods: {

    }
  }
</script>

<!-- scoped局部 -->
<!-- @代表项目根路径,css为全局,scss为局部并支持所以css语法 -->
<style>
  @import "../../assets/css/common.scss";

</style>

3. 设置route目录:

新增文件/src/route/route.js,

route.js全部代码(引用的config在如下代码直接删除即可,这是我自定义的东西):

// 注册路由,vue3+vite专用
import {config} from "../config/config";
const page_path = '../pages/';

const routes = [ // 自定义路由名称
    { // 必要
        path: '/404',
        component: () => import(page_path + '404/404.vue'),
        meta: { title: '404,没有对应该路由页面' },
    },
    { // 必要
        path: '/',
        component: () => import(page_path + 'home/home.vue'),
        meta: { title: '首页' },
    },

    { // 示例
        path: '/example',
        component: () => import(page_path + 'example/example.vue'),
        meta: { title: '示例1' },
    },
    { // 示例
        path: '/example/test',
        component: () => import(page_path + 'example/example2.vue'),
        meta: { title: '示例2' },
    },
    { // 示例
        path: '/editor',
        component: () => import(page_path + 'editor/editor.vue'),
        meta: { title: '富文本编辑器' },
    },
    { // 示例
        path: '/swiper',
        component: () => import(page_path + 'swiper/swiper.vue'),
        meta: { title: 'swiper' },
    },
    { // 示例
        path: '/chart',
        component: () => import(page_path + 'chart/chart.vue'),
        meta: { title: 'chart' },
    },

    // 其他路由


];


// 文档https://next.router.vuejs.org/zh/guide/migration/index.html#%E5%88%A0%E9%99%A4-router-match-%E6%94%B9%E4%B8%BA-router-resolve
import { createRouter, createWebHistory } from 'vue-router'

// 路由模式
const router = createRouter({
    history: createWebHistory(),
    routes: routes,
});

// 监控路由
router.beforeEach((to, from, next) => {
    if (to.matched.length === 0) {  // 未匹配到路由
        next('/404');
    } else { // 匹配到路由
        // 修改页面title
        let page_title = '';
        try {
            page_title = to.meta.title;
        }catch (e) {
            page_title = '(没有配置meta.title名)';
        }
        if (page_title) {
            document.title = page_title + " - " + config.title;
        }else{
            document.title = config.title;
        }
        next();
    }
});

export default router;

4.设置使用axios:

也可用原生fetch代替axios请求。

组件全部代码如下:

<template>
    <div class="section-must" v-loading="loading">must</div>
</template>

<script>

    import axios from "axios";

    export default {
        name: "must",
        data(){
            return {
                loading: true,
            };
        },
        mounted() { // 组件初始化完成
            let that = this;
            that.common.log('=must=mounted');
            // 获取token
            that.get_app_token();
        },
        methods: { // 组件局部函数集合
            page_init: function (txt) {
                let that = this;
                that.common.log(txt);
                that.loading = false;
                try {
                    that.$parent.start_this_page(txt);
                }catch (e) {
                    console.error("报错情况:1.子页面start_this_page()函数未定义,但是可以忽略;2.子页面函数有错误,必须解决。\n\n参考如下:");
                    console.error(e);
                }
            },
            get_app_token: function () { // 获取页面app_token参数
                let that = this;

                // 验证必要参是否完整
                let app_class = that.config.app.app_class;
                let app_token = that.common.get_cookie("app_token");
                if (!app_class){
                    that.common.log("必要参数不完整,运行中断");
                    return;
                }
                if (app_token && app_token !== "undefined"){
                    that.common.log("必要参数完整,不必再次请求");
                    that.page_init(["=get_app_token=check", "must"]);
                    return;
                }

                // 获取必要参数

                // // 开始-Fetch-请求数据
                // const post_api = that.config.api_url + "app/get_app_token"; // 接口
                // const map = new Map([ // 要提交数据
                //     ["app_class", that.config.app.app_class],
                //     ["app_name", that.config.app.app_name],
                //     ["url", encodeURI(window.location.href).substring(0, 2000)], // 取当前url即可
                // ]);
                // let body = "";
                // for (let [k, v] of map) { body += k+"="+v+"&"; } // 拼装数据,限制2MB
                // fetch(post_api, {
                //     method: "post",
                //     mode: "cors", // same-origin/no-cors/cors
                //     cache: "no-cache",
                //     headers: {
                //         "Content-type": "application/x-www-form-urlencoded; charset=UTF-8",
                //     },
                //     body: body,
                // }).then(function(response){
                //     if (response.status === 200){return response;}
                // }).then(function(data) {
                //     return data.text();
                // }).then(function(text){ // 返回接口数据
                //     let res = that.common.data_to_json(text);
                //     that.common.log(res);
                //
                //     that.loading = false;
                //
                //     if (res.state === 0){
                //         that.common.log(res.msg);
                //         that.$message(res.msg);
                //
                //         that.login_txt = res.msg;
                //
                //     }else if (res.state === 1){
                //         that.common.log(res.msg);
                //         // that.$message("生成完成");
                //
                //         // 兼容老接口写法
                //         let app_token = res.content.app_token;
                //         if (app_token === 'undefined' || !app_token){
                //             app_token = res.content.user_token;
                //         }
                //
                //         that.common.set_cookie("app_token", app_token, that.common.cookie_timeout);
                //
                //         setTimeout(function () {
                //             that.page_init(["=get_app_token=request", "must"]);
                //         }, 10);
                //
                //     }else if (res.state === 2){
                //         that.common.log(res.msg);
                //         that.$message(res.msg);
                //         that.login_txt = res.msg;
                //
                //     }else if (res.state === 302){ // 需要重新获取参数(登录)
                //         that.common.log(res.msg);
                //         that.$message(res.msg);
                //         that.login_txt = res.msg;
                //
                //
                //     }else{ // "超范围的参数"
                //         that.$message("超范围的参数");
                //         that.common.log(res.msg);
                //     }
                //
                // }).catch(function(error){
                //     let error_info = "Fetch_Error:" + error;
                //     that.$message.error("Fetch_Error:" + error);
                //     that.common.error(error_info);
                //
                // });
                // // 结束-Fetch

                // POST请求
                axios.post(
                    that.config.api_url + "app/get_app_token", // 设置了baseUrl就不需要连接主域名
                    {
                        app_class: that.config.app.app_class,
                        app_name: that.config.app.app_name,
                        url: encodeURI(window.location.href).substring(0, 2000),
                    }, {
                        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
                    }
                )
                    .then(function (back) {
                        let res = back.data;
                        that.loading = false;

                        if (res.state === 0){
                            that.common.log(res.msg);
                            // that.$message.error(res.msg);

                        }else if (res.state === 1){
                            that.common.log(res.msg);
                            that.$message("生成完成");

                            // 兼容老接口写法
                            let app_token = res.content.app_token;
                            if (app_token === 'undefined' || !app_token){
                                app_token = res.content.user_token;
                            }

                            that.common.set_cookie("app_token", app_token, that.common.cookie_timeout);

                            setTimeout(function () {
                                that.page_init(["=get_app_token=request", "must"]);
                            }, 10);

                        }else if (res.state === 2){
                            that.common.log(res.msg);
                            that.$message.error(res.msg);

                        }else if (res.state === 302){ // 需要重新获取参数(登录)
                            that.common.log(res.msg);
                            that.$message.error(res.msg);

                        }else{ // "超范围的参数"
                            that.$message.error('超范围的参数');
                            that.common.log(res.msg);
                        }

                    })
                    .catch(function (e) {
                        console.error(e);
                        that.$notify({
                            title: '警告',
                            message: '网络不通或接口请求错误',
                            type: 'warning'
                        });
                    });

            },

        },

    }
</script>

<style scoped>
    .section-nav{
        width: 100%;
    }
</style>

 

 

 

 

 

 

 

 

上一篇:Java调用第三方http接口_通过apache common封装好的HttpClient


下一篇:npm-link基本使用