当前位置:   article > 正文

vue3框架搭建+vite+ts+elementplus+axios+vuex_vue3+vite+ts+elementplus的安装和使用教程

vue3+vite+ts+elementplus的安装和使用教程

1. window+R打开命令行 输入

npm create vite@latest
  • 1

按照如下步骤创建
在这里插chuang入图片描述
在这里插入图片描述
在这里插入图片描述

2. 进入项目下载依赖

在这里插入图片描述

3. 依赖安装好后运行项目

在这里插入图片描述

4.引入element-plus

npm install element-plus --save

main.js里引入
import ElementPlus from 'element-plus'
import 'element-plus/dist/index.css'
const app = createApp(App).use(ElementPlus)
app.mount('#app')

使用el-icon需要另外下载引入
npm install @element-plus/icons-vue

main.js里引入
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

5.配置路由

npm install vue-router 
  • 1

main.js里引入路由

import router from './router'
const app = createApp(App).use(ElementPlus).use(router)
  • 1
  • 2

新建router文件
![在这里插入图片描述](https://img-blog.csdnimg.cn/ecd8b53e8d2d47768a7ef702476d39bd.png

import { createRouter, createWebHashHistory } from "vue-router"
const routes = [

    {

        path: '/',

        name: 'index',

        component: () => import('../views/index.vue')

    },

    {

        path: '/login',

        name: 'login',
        component: () => import('../views/login.vue')

    }

]

export const router = createRouter({

    history: createWebHashHistory(),

    routes: routes

})

export default router
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33

注意:一定要在app.vue内添加router-view!!!
在这里插入图片描述

6.axios封装接口器请求

npm i axios
npm i qs
  • 1
  • 2

新建request>axios.js文件
在这里插入图片描述

/**axios封装
 * 请求拦截、相应拦截、错误统一处理
 */
import axios from 'axios';
import QS from 'qs';
import router from '../router/index'
//qs.stringify()是将对象 序列化成URL的形式,以&进行拼接
//  let protocol = window.location.protocol; //协议
//  let host = window.location.host; //主机
//  axios.defaults.baseURL = protocol + "//" + host;
axios.defaults.baseURL = 'http://localhost:8888'
 
axios.interceptors.request.use( //响应拦截
        async config => {
            // 每次发送请求之前判断vuex中是否存在token        
            // 如果存在,则统一在http请求的header都加上token,这样后台根据token判断你的登录情况
            // 即使本地存在token,也有可能token是过期的,所以在响应拦截器中要对返回状态进行判断 
            config.headers.token = sessionStorage.getItem('token')
            return config;
        },
        error => {
            return Promise.error(error);
        })
    // 响应拦截器
axios.interceptors.response.use(
    response => {
        if (response.status === 200) {
            return Promise.resolve(response); //进行中        
        } else {
            return Promise.reject(response); //失败       
        }
    },
    // 服务器状态码不是200的情况    
    error => {
        if (error.response.status) {
            switch (error.response.status) {
                // 401: 未登录                
                // 未登录则跳转登录页面,并携带当前页面的路径                
                // 在登录成功后返回当前页面,这一步需要在登录页操作。                
                case 401:
                    break
                    // 403 token过期                
                    // 登录过期对用户进行提示                
                    // 清除本地token和清空vuex中token对象                
                    // 跳转登录页面                
                case 403:
                    sessionStorage.clear()
                    router.push('/login')
                    break
                    // 404请求不存在                
                case 404:
                    break;
                    // 其他错误,直接抛出错误提示                
                default:
            }
            return Promise.reject(error.response);
        }
    }
);
/** 
 * get方法,对应get请求 
 * @param {String} url [请求的url地址] 
 * @param {Object} params [请求时携带的参数] 
 */
const $get = (url, params) => {
        return new Promise((resolve, reject) => {
            axios.get(url, {
                    params: params,
                })
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err.data)
                })
        });
    }
    /** 
     * post方法,对应post请求 
     * @param {String} url [请求的url地址] 
     * @param {Object} params [请求时携带的参数] 
     */
const $post = (url, params) => {
        return new Promise((resolve, reject) => {
            axios.post(url, QS.stringify(params)) //是将对象 序列化成URL的形式,以&进行拼接   
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err.data)
                })
        });
    }
    //下面是vue3必须加的,vue2不需要,只需要暴露出去get,post方法就可以
export default {
    install: (app) => {
        app.config.globalProperties['$get'] = $get;
        app.config.globalProperties['$post'] = $post;
        app.config.globalProperties['$axios'] = axios;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101

main.js内引入

import Axios from './request/axios';
app.use(ElementPlus).use(Axios)
  • 1
  • 2

进入需要发送请求的页面

import {  getCurrentInstance } from "vue";
const { proxy } = getCurrentInstance();
function logout() {
  proxy
    .$post("/api/qrycontent/", {
      page: 1,
      perpage: 4,
      section: "LearningGarden",
    })
    .then((response) => {
      console.log(response);
      if (response.code == 200) {
        sessionStorage.clear();
        router.push("/");
        ElMessage({
          message: "退出成功",
          type: "success",
        });
      }
    });
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

7.到这一步接口会请求不通,因为还没有配置跨域,接着配置跨域

在这里插入图片描述

  server: {
    proxy: {
      '/api': {
        target: 'http://------------/', // 实际请求地址
        changeOrigin: true,
        rewrite: (path) => path.replace(/^\/api/, "/api"),
      },
    },
  },
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

8.使用vuex

npm i vuex
  • 1

main.js引入

import store from './store'
const app = createApp(App).use(router).use(ElementPlus).use(Axios).use(store)
  • 1
  • 2

新建store>index.js
在这里插入图片描述

/*
 * @Author: wangdandan 15249780720@163.com
 * @Date: 2023-10-17 11:16:03
 * @LastEditors: wangdandan 15249780720@163.com
 * @LastEditTime: 2023-10-17 14:08:00
 * @FilePath: \vue3-practice\src\store\index.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { createStore } from 'vuex'
// 类似 Redux 中的建立状态树

export default createStore({
  
  // 1、 存储所有全局数据
  state: {
    person:{
        name:'jack',
        age:20
    }
  },
 
  // 2、 需要通过计算获取state里的内容获取的数据
  // 只能读取不可修改
  getters: {
    getPerson(state){
        return state.person
    }
  },
 
  //  3、定义对state的各种操作
  // why不直接实现在mutation里需要写到action里?
  // mutations不能执行异步操作。aq:从云端获取信息-->(等待云端反馈)更新到state异步操作
  // 因此说:对于异步操作需要放到action里,简单的直接赋值操作可以直接放到mutation里
  mutations: {
   ageGrow(state,value){
    state.person.age += value
   }
  },

  // 3、定义对state的各种操作
  // actions无法直接修改state,需要在mutations里更新
  // mutation不支持异步,所以需要在action里写api到url
  actions: {
      // 比说action定义了更新state的操作
      // 但是不可对其直接修改
      // 所有的修改操作必须放到mutations里
      ageGrow(store,value){
        store.commit('ageGrow',value)
       }
  },

  // state中信息过长时
  // 用来将state进行分割
  // 如下,将state树分割出一个user state。
  modules: {
	// user: ModuleUser,
  }
})


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60

在页面使用

import { useStore } from "vuex";
  • 1

在这里插入图片描述

在这里插入图片描述

  <h2>----------vuex使用-------------</h2>
  <h3>名字:{{store.state.person.name}} ------------ 年龄:{{store.state.person.age}}</h3>
  <el-button @click="changeAge">同步改变年龄</el-button>
  <el-button @click="asycChangeAge">异步改变年龄</el-button>


// vuex
const store = useStore();
// 同步改变vuex数据
const changeAge = () =>{
  store.commit('ageGrow',1)
}
// 异步改变vuex数据
const asycChangeAge = () =>{
  setTimeout(() => {
    store.dispatch('ageGrow',2)
  }, 100);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

9.配置环境变量

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

# just a flag
ENV = 'development'

# base api
VITE_APP_BASE_API = 'http://----------------/'

# title
VITE_APP_TITLE = '开发环境'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

axios内修改url

 axios.defaults.baseURL = '/api';
  • 1

vite.config.js内修改
在这里插入图片描述

import path from "path";
import { defineConfig, loadEnv } from 'vite';
import vue from '@vitejs/plugin-vue';

// https://vitejs.dev/config/
export default ({ mode }) => {
  //参数mode为开放模式或生产模式
  //console.log(mode);  // development or product
  const env=loadEnv(mode, process.cwd());   // 获取.env文件里定义的环境变量
  console.log(env);   //变量在命令行里打印出来
  
  return defineConfig({
    plugins: [vue()],

    //项目部署在主域名的子文件使用,例如http://localhost:3000/myvite/。不填默认就是/
    base: env.VITE_APP_BASE_URL,
    build: {
      cssCodeSplit: false, //默认ture,将css分割提取到css文件中,false将全部css提取到一个文件里
    },

    resolve: {
      alias: {
        //别名配置
        "@": path.resolve(__dirname, "src"), //配置src的别名
        "@comp": path.resolve(__dirname, "src/components"),
      },
    },
    server: {
      proxy: {
        // 代理配置
        "/api": {
          // target: "http://127.0.0.1/1000", //本地服务器环境后台目录D:\phpstudy_pro\WWW\1000
          target: env.VITE_APP_BASE_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/api/, "/api"),
        },
      },
    },
  })
}


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小桥流水78/article/detail/883582?site
推荐阅读
相关标签
  

闽ICP备14008679号