赞
踩
npm i axios
说明:request.js文件
- //对axios进行二次封装
- import axios from "axios"
- import "nprogress/nprogress.css"
-
- // 当前模块中引入store
- // import store from "@/store"
-
- // 引入进度条
-
- import nprogress from "nprogress"
-
- // start代表进度条开始,done表示进度条结束
-
- // 创建axios实例,其实request就是axios
- const requests = axios.create({
- // 发请求的时候自动出现api
- // baseURL:"api",
- // 请求超时的时间
- timeout: 5000,
-
- })
- // 请求拦截器,
- requests.interceptors.request.use((config) => {
- // config对象中有一个headers请求头
-
- // 进度条开始
- // if (store.state.detail.uuid_token) {
- // // 请求头添加一个字段userTempId
- // config.headers.userTempId = store.state.detail.uuid_token
- // }
- // 判断需要携带token带到服务器
- // if (store.state.user.token) {
- // config.headers.token = store.state.user.token
- // }
- nprogress.start()
- return config
- })
-
- // 响应拦截器
- requests.interceptors.response.use(config => {
- // 成功的回调函数,服务器相应数据回来以后,响应拦截器可以检测到
- // 进度条结束
- nprogress.done()
- return config.data
- }, error => {
- console.log(error);
- return Promise.reject(new Error("fail"))
- })
-
-
- export default requests
说明:index.js文件暴露请求方法。
- //导入封装的axios
- import request from "./request";
-
- export const getData=()=>{
- return request({url:"./data.json",method:'GET'})
- }
说明:将请求方法挂载在vue的原型上面。
- import Vue from 'vue';
-
-
- import 'element-ui/lib/theme-chalk/index.css';
-
- import ElementUI from 'element-ui';
-
- import router from "./router/index.js"
-
- import store from "./store/index.js";
-
- import App from './App.vue';
-
-
-
- Vue.use(ElementUI);
-
- //导入api文件
- import * as API from "@/api"
-
- new Vue({
- el:"#app",
- router,
- store,
- beforeCreate() {
- // 挂载vue实例原型身上,一般自己添加的原型都以$命名
- Vue.prototype.$API = API;
- },
- render:(h)=>h(App),
- }).$mount();
- <template>
- <div>
- <h1>{{ title }}</h1>
- </div>
- </template>
-
-
- <script>
- export default {
- name: "Index",
- data() {
- return {
- title: '',
- }
- },
- methods: {
- async getData() {
- let res = await this.$API.getData()
- //解构title
- let {title}=res
- this.title=title
- }
- },
- mounted() {
- this.getData()
- }
- }
- </script>
-
- <style scoped></style>
说明:data.json文件,被请求的文件放置最外层,与src文件同级。
- import {createVuePlugin} from "vite-plugin-vue2"
-
-
- export default {
- plugins: [createVuePlugin({
- // 使用 Element UI
- globalComponents: true,
- })],
- server: {
- open: true, //自动打开浏览器
- port: 80, //端口
- },
- resolve:{
- //别名
- alias: [
- {
- find: '@',
- replacement: '/src'
- }
- ]
- }
-
- }
9.依赖包
- {
- "name": "vite-vue2",
- "private": true,
- "version": "0.0.0",
- "scripts": {
- "dev": "vite",
- "build": "vite build",
- "preview": "vite preview"
- },
- "devDependencies": {
- "babel-plugin-component": "^1.1.1",
- "vite": "^2.9.15",
- "vite-plugin-vue2": "^1.9.3"
- },
- "dependencies": {
- "axios": "^1.6.2",
- "echarts": "^5.4.3",
- "element-ui": "^2.8.2",
- "nprogress": "^0.2.0",
- "vue": "^2.7.15",
- "vue-router": "^3.5.2",
- "vue-template-compiler": "^2.7.15",
- "vuex": "^3.6.2"
- }
- }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。