vue3+vite:route路由、axios请求(跨域)、vite.config.js打包生产环境、ele-ui-plus等

Vue3+vite+axios+route示例全部源代码,包含所有依赖,可直接运行。下载(等待平台审核后可下载):https://download.csdn.net/download/weixin_41827162/16035637

0. 安装vue3+vite:

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


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

1. 安装route、axios等插件依赖:

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/下:

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";

import home from '../pages/home/home.vue';
import page_404 from '../pages/404/404.vue';

import example from '../pages/example/example.vue';
import example_test from '../pages/example/test/test.vue';
import editor from '../pages/editor/editor.vue';
import swiper from '../pages/swiper/swiper.vue';
import chart from '../pages/chart/chart.vue';
import qr from '../pages/qr/qr.vue';
import js from '../pages/js/js.vue';
import upload_img from '../pages/upload_img/upload_img.vue';
import emit_page1 from '../pages/emit/page1.vue';
import emit_page2 from '../pages/emit/page2.vue';

const routes = [ // 自定义路由名称
    { // 必要
        path: '/404',
        component: page_404,
        meta: { title: '404,没有对应该路由页面' },
    },
    { // 必要
        path: '/',
        component: home,
        meta: { title: '首页' },
    },

    /*示例*/
    { // 示例
        path: '/example',
        component: example,
        meta: { title: '示例1' },
    },
    { // 示例
        path: '/example/test',
        component: example_test,
        meta: { title: '示例2' },
    },
    { // 示例
        path: '/editor',
        component: editor,
        meta: { title: '富文本编辑器' },
    },
    { // 示例
        path: '/swiper',
        component: swiper,
        meta: { title: 'swiper' },
    },
    { // 示例
        path: '/chart',
        component: chart,
        meta: { title: 'chart' },
    },
    { // 示例
        path: '/qr',
        component: qr,
        meta: { title: '合成二维码' },
    },
    { // 示例
        path: '/js',
        component: js,
        meta: { title: 'js处理元素、数组等' },
    },
    { // 示例
        path: '/upload_img',
        component: upload_img,
        meta: { title: '上传图片' },
    },
    { // 示例
        path: '/emit/page1',
        component: emit_page1,
        meta: { title: 'page1' },
    },
    { // 示例
        path: '/emit/page2',
        component: emit_page2,
        meta: { title: 'page2' },
    },

    /*其他路由*/


];


// 文档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

                // 严格的提交数据格式
                const map = new Map([ // 要提交数据
                    ["id", 20221],
                    ["nickname", "map-body-k-v"],
                ]);
                const body = new URLSearchParams();
                for (let [k, v] of map) { body.append(k, v+""); }
                axios.post(post_api, body, {headers: {"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"}
                }).then(function (back) {
                        let res = back.data;
                        console.log(res)

                    })
                    .catch(function (e) {
                        console.error(e);
                    });


                // 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>

5. 打包:

项目根目录新增文件vite.config.js,内容如下:

const path = require('path');
// vite.config.js # or vite.config.ts

console.log(path.resolve(__dirname, './src'));

module.exports = {
    /**
     * 在生产中服务时的基本公共路径。
     * @default '/'
     */
    base: './',
    /**
     * 与“根”相关的目录
     * @default 'dist'
     */
    outDir: 'dist',
    port: 3000,
    // 是否自动在浏览器打开
    open: true,
    // 是否开启 https
    https: false,
    // 服务端渲染
    ssr: false,
    // 引入第三方的配置
    optimizeDeps: {
        include: ["moment", "echarts", "axios", "mockjs"]
    },
    alias: {
        // 键必须以斜线开始和结束
        '/@/': path.resolve(__dirname, './src')
        // '/@components/': path.resolve(__dirname, './src/components')
    },
    proxy: {
        
    }
};

 

6. 访问:

 

--

--

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值