• 四、网络请求与路由


    一、网络请求

    1、Axios请求

    Axios是一个基于promise的网络请求库

    (1)安装

    npm install --save axios
    
    • 1

    (2)引入

    import axios from "axios"
    
    全局引入
    import axios from "axios"
    import { createApp } from 'vue'
    import App from './App.vue'
    
    const app = createApp(App);
    app.config.globalProperties.$axios = axios;
    app.mount('#app');
    
    // 调用方式 this.$axios
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    (3)网络请求基本示例

    get请求

    axios({
    	method: "get",
    	url:"http://xxx.com"
    }).then(res => {
    	console.log(res.data);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    post请求
    参数需要处理为字符串
    安装依赖 npm install --save querystring
    引入:import qs from “querystring”
    使用:qs.stringify({})

    axios({
    	method: "post",
    	url:"http://xxx.com/xxx",
    	data:{
    		id:"xxx"
    	}
    }).then(res => {
    	console.log(res.data);
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    (4)快捷请求

    get请求

    axiso.get("http://xxx.com/xxx").then( res=>{console.log(res.data);} )
    
    • 1

    post请求

    axiso.post("http://xxx.com/xxx", qs.stringify({ id:"xxx" })).then( res=>{console.log(res.data);} )
    
    • 1

    二、网络请求封装

    1、网络请求封装

    创建js文件(在/src/utils)request.js
    
    • 1
    import axios from "axios"
    import querystring from "querystring"
    
    // 创建网络对象
    const instance = axios.create({
    	// 配置网络请求公共参数
    	timeout:3000
    })
    
    // 请求拦截,发送之前的注册
    instance.interceptors.request.use(
    	config = >{ // 请求成功
    		if(config.methods === "post"){
    			config.data = qs.stringify(config.data)
    		{
    		// config包括网络请求所有信息
    		return config;
    	},
    	error =>{ //请求失败
    		return Promise.reject(error);
    	}
    )
     
    // 响应拦截,获取数据之前
    instance.interceptors.response.use(
    	response =》{
    		return response.status === 200 ? Promise.resolve(response) : Promise.reject(response)
    	},
    	error =>{ //请i去失败
    		const { response } = error;
    		console.log(response.status);
    	{
    {
    
    
    • 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

    2、接口调用

    创建文件:path.js(或者base.js)j 和 index.js
    
    • 1
    // path.js
    const base ={
    	baseUrl: "http://xxx.com",
    	path1:"/api/aaa"
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    // index.js
    import axios from "../utils/request"
    impoer path from "./path"
    
    const api = {
    	getPath1(){
    		return axios.get(path.baseUrl + path.path1);
    	}
    }
    
    const default api
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    // vue文件
    import api from "../api/index"
    
    export default{
    	......
    	mounted(){
    		api.getPath1().then( res =?{
    			console.log(res.data);
    		})
    	}
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    三、跨域问题解决

    1、问题原有

    js采用的时同源策略,浏览器只允许js代码请求和当前服务器的域名、端口、协议相同的数据接口的数据。当协议、域名、端口,任意一个不相同时,就会产生跨域问题。
    
    • 1

    在这里插入图片描述

    2、解决方案proxy

    (1)修改配置

    // vue.config.js
    const { defineConfig } = require('@vue/cli-service')
    module.exports = defineConfig({
      transpileDependencies: true,
      devServer: {
        proxy: {
          "/api": {
            target: "https://ip.cn",
            changeOrigin: true
          }
        }
      }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    (2)将请求地址前面的域名删除,之后重启

    this.$axios({
                methos: "get",
                url: "/api/index?ip=&type=0"
            }).then(
                res => {
                    console.log(res.data);
                }
            )
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    三、vue引入路由配置(页面跳转)

    1、创建附带路由的项目

    Vue CLI v5.0.8
    ? Please pick a preset: Manually select features
    ? Check the features needed for your project: (Press  to select,  to toggle all,  to invert selection, and  to 
    proceed)
     (*) Babel
     ( ) TypeScript
     (*) Progressive Web App (PWA) Support
    >(*) Router	//路由选项
     ( ) Vuex
     ( ) CSS Pre-processors
     ( ) Linter / Formatter
     ( ) Unit Testing
     ( ) E2E Testing
    

    2、使用路由

    (1)使用路由

    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    (2)配置路由

    // vue-router\src\router\index.js
    import { createRouter, createWebHashHistory } from 'vue-router'
    import HomeView from '../views/HomeView.vue'
    
    const routes = [
      {
        path: '/',
        name: 'home',
        component: HomeView
      },
      {
        path: '/about',
        name: 'about',
        // 异步加载,没有被点击不会加载
        component: () => import("../views/AboutView.vue")
      }
    ]
    
    const router = createRouter({
      /**
     * createWebHashHistory
     *      home:http://localhost:8080/#/
     *      about:http://localhost:8080/#/about
     * 
     *  原理:a标签锚点连接
     */
      /**
       * createWebHistory
       *      home:http://localhost:8080/
       *      about:http://localhost:8080/about
       * 此种方式,需要后台配合做重定向,否则会出现404问题
       * 
       * 原理:H5 pushState()
       */
      history: createWebHashHistory(),
      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
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    (3)主页内容

    
    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    (4)关于页面内容

    
    
    
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    四、路由传递参数

    1、在路径中指定参数的key

     {
        path: "/news/info/:msg",
        name: "mewsinfo",
        component: () => import("../views/NewsInfoView.vue")
      }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    2、在跳转中设置参数

    		
  • 百度新闻
  • 网易新闻
  • 头条新闻
    • 1
    • 2
    • 3

    3、接收参数

    
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    五、嵌套路由

    1、嵌套路由

    // vue-router\src\router\index.js
    import { createRouter, createWebHashHistory } from 'vue-router'
    import HomeView from '../views/HomeView.vue'
    
    const routes = [
      {
        path: '/',
        name: 'home',
        component: HomeView
      },
      {
        path: '/about',
        name: 'about',
        // 异步加载,没有被点击不会加载
        component: () => import("../views/AboutView.vue")
      },
      {
        path: "/news",
        name: "mews",
        // 重镜像,默认选择baidu
        redirect: "/news/baidu",
        component: () => import("../views/NewsView.vue"),
        children: [
          {
            path: "baidu",
            component: () => import("../views/NewsBaiduView.vue")
          },
          {
            path: "wangyi",
            component: () => import("../views/NewsWangyiView.vue")
          }
        ]
      }
    ]
    
    const router = createRouter({
      history: createWebHashHistory(),
      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
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41

    在这里插入图片描述

  • 相关阅读:
    kodi的IPTV直播源爬取
    免费热门api分享,含物流、短信、天气查询等
    为什么你懂很多道理,偏偏就是不会赚钱?
    Java 线程池将数据从主线程传到子线程
    CSS之垂直水平居中的背后
    【uiautomation】微信群发消息,可发送文本 & 文件
    SMARTPHONE PLATFORM st解决方案
    初识Docker
    break pad源码编译--参考大佬博客的总结
    Docker&Kubernetes ❀ Service下Port端口区分
  • 原文地址:https://blog.csdn.net/liutit/article/details/133967198