• vue3 + vite + ts 搭建项目


    1.通过vite 脚手架

    npm init vite hello-vue3 -- --template vue

    2.按装依赖,启动项目

      npm i

      npm run dev

    3.修改vite配置文件

      找到vite.confing.ts   并添加

    import { defineConfig } from 'vite'
    import vue from '@vitejs/plugin-vue'
    import { resolve } from 'path'

    // https://vitejs.dev/config/
    export default defineConfig({
    resolve: {
    alias: {
    '@': resolve(__dirname, 'src'),
    }
    },
    plugins: [vue()],
    base: './', // 打包路径
    server: {
    port: 3000, // 服务端口号
    open: true, // 服务启动时是否自动打开浏览器
    cors: true, // 允许跨域
    proxy:{
    '/api':{
    target:'http://www.xxxx.com.cn',
    changeOrigin:true,
    rewrite:(path) =>path.replace('/api','')
    }
    }
    }
    })
    注:这块会有找不到path 的问题,我们需要先安装类型声明文件
    npm install --save-dev @types/node

    4.添加路由

       安装 npm i vue-router@4

        创建 src/router/index.ts 文件

     main.ts 文件中挂载 

    import router from './router/index'
    createApp(App).use(router).mount('#app');

      5.添加vuex

        安装npm i vuex@next

        创建 src/store/index.ts 文件

     main.ts 文件中挂载 

    import storefrom './store'
    createApp(App).use(store).mount('#app');
    用法:
    import { useStore } from 'vuex';
    const store = useStore();
    console.log(store.state);

     6.添加axios

        安装npm i axios

        创建 src/api/axios.ts 文件

        创建 src/api/api.ts 文件

     main.ts 文件中挂载 

    import axios from './api/axios'
    import api from './api/index'

    const app = createApp(App);
    app.config.globalProperties.$axios = axios;
    app.config.globalProperties.$api = api;
    这里需要用到全局挂载变量
    注:axios.ts文件里为axios的封装
    index.ts是将所有的接口定义整合
    let api:any = {}
    let apiFiles = import.meta.globEager('./**/*.ts');
    let model: any = {};
    for (const key in apiFiles) {
    if(key!='./axios.ts'){
    if (Object.prototype.hasOwnProperty.call(apiFiles, key)) {
    model[key.replace(/(\.\/|\.ts)/g, '')] = apiFiles[key].default;
    }
    }

    }
    for (const key in model) {
    api = Object.assign({},model[key])
    }
    export default api;

    下面这个是所有接口的内容
    export default {
    data1: '/querySupplierTypeList', //列表
    data: '/data/sk/101010100.html', //html
    }
    在页面中的用法:
    import { getCurrentInstance } from 'vue';
    const store = useStore();
    const { proxy } =getCurrentInstance();
    const message =store.state.massage;
    console.log(proxy.$api.data);
    const fun = ()=>{
    proxy.$axios({
    url:proxy.$api.data,
    method:'get',
    data:{}
    })
    }

    最后重新启动一下我们的项目:
    npm run dev
  • 相关阅读:
    一、cocos2d-x 3.0 final使用httpclient编译到android,须要用到的android.mk
    lvchange的available參数
    基于谱减法的声音去噪
    ios使用openUrl进行应用跳转
    linux下ssh免密登陆
    字体图标 icon font
    hdu 3642 Get The Treasury(扫描线)
    3D游戏引擎一 win32编程
    Codeforces 112B-Petya and Square(实现)
    动态规划 is beginning。。。。。。。。。
  • 原文地址:https://www.cnblogs.com/xiebeibei/p/15728374.html
Copyright © 2020-2023  润新知