四、网络请求与路由

news2024/10/6 4:12:15

一、网络请求

1、Axios请求

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

(1)安装

npm install --save axios

(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

(3)网络请求基本示例

get请求

axios({
	method: "get",
	url:"http://xxx.com"
}).then(res => {
	console.log(res.data);
})

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);
})

(4)快捷请求

get请求

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

post请求

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

二、网络请求封装

1、网络请求封装

创建js文件(在/src/utils)request.js
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);
	{
{

2、接口调用

创建文件:path.js(或者base.js)j 和 index.js
// path.js
const base ={
	baseUrl: "http://xxx.com",
	path1:"/api/aaa"
}

// index.js
import axios from "../utils/request"
impoer path from "./path"

const api = {
	getPath1(){
		return axios.get(path.baseUrl + path.path1);
	}
}

const default api

// vue文件
import api from "../api/index"

export default{
	......
	mounted(){
		api.getPath1().then( res =?{
			console.log(res.data);
		})
	}
}

三、跨域问题解决

1、问题原有

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

在这里插入图片描述

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
      }
    }
  }
})

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

this.$axios({
            methos: "get",
            url: "/api/index?ip=&type=0"
        }).then(
            res => {
                console.log(res.data);
            }
        )

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

1、创建附带路由的项目

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

2、使用路由

(1)使用路由

<!-- vue-router\src\App.vue -->
<template>
  <router-link to="/">首页</router-link> |
  <router-link to="/about">关于</router-link>
  <router-view></router-view>
</template>

<style></style>

(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

(3)主页内容

<!-- vue-router\src\views\HomeView.vue -->
<template>
  <div>
    <h1>主界面</h1>
  </div>
</template>

<script>

export default {
  name: 'HomeView'
}
</script>

(4)关于页面内容

<!-- vue-router\src\views\AboutView.vue -->
<template>
  <div>
    <h1>关于页面</h1>
  </div>
</template>

<script>
export default {
  name: 'AboutView'
}
</script>

四、路由传递参数

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

 {
    path: "/news/info/:msg",
    name: "mewsinfo",
    component: () => import("../views/NewsInfoView.vue")
  }

2、在跳转中设置参数

		<li><router-link to="/news/info/百度新闻">百度新闻</router-link></li>
        <li><router-link to="/news/info/网易新闻">网易新闻</router-link></li>
        <li><router-link to="/news/info/头条新闻">头条新闻</router-link></li>

3、接收参数

<template>
    <p>{{ $route.params.msg }}: 新闻详情</p>
</template>

在这里插入图片描述

五、嵌套路由

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

在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1121795.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

深度学习_3_实战_房价预测

梯度 实战 代码&#xff1a; # %matplotlib inline import random import torch import matplotlib.pyplot as plt # from d21 import torch as d21def synthetic_data(w, b, num_examples):"""生成 Y XW b 噪声。"""X torch.normal(0,…

面试知识储备--打包工具篇(webpack和vite)

1.vite常用配置 常用配置 1.preprocessorOptions 传递给 CSS 预处理器的配置选项 2.PostCSS 也是用来处理 CSS 的&#xff0c;只不过它更像是一个工具箱&#xff0c;可以添加各种插件来处理 CSS 3.resolve.extensions 导入时想要省略的扩展名列表。默认值为 [‘.mjs’, ‘.js’…

小团队之间有哪些好用免费的多人协同办公软件

在小团队协作中&#xff0c;选择适合的多人协同办公软件是提高工作效率和团队协作的重要一环。幸运的是&#xff0c;市场上有许多大多数功能都免费的多人协同办公软件&#xff0c;为小团队提供了强大的协作功能和便捷的工作环境。 在本文中&#xff0c;我将根据自己多年的在线…

2.2.C++项目:网络版五子棋对战之数据管理模块的设计

文章目录 一、数据管理模块实现&#xff08;一&#xff09;功能 二、设计&#xff08;一&#xff09;数据库设计&#xff08;二&#xff09;创建user_table类 一、数据管理模块实现 &#xff08;一&#xff09;功能 数据管理模块主要负责对于数据库中数据进行统一的增删改查管…

3ds Max2023安装教程(最新最详细)

目录 一.简介 二.安装步骤 软件&#xff1a;3ds Max版本&#xff1a;2023语言&#xff1a;简体中文大小&#xff1a;6.85G安装环境&#xff1a;Win11/Win10/Win8/Win7硬件要求&#xff1a;CPU3GHz 内存16G(或更高&#xff09;下载通道①百度网盘丨64位下载链接&#xff1a; …

【蓝桥每日一题]-动态规划 (保姆级教程 篇10)#方格取数

高能预警&#xff1a;讲了这么久动态规划了&#xff0c;该上点有难度的题吧 目录 题目&#xff1a;方格取数 思路&#xff08;解法一&#xff09;&#xff1a; 解法二&#xff1a; 题目&#xff1a;方格取数 思路&#xff08;解法一&#xff09;&#xff1a; 如果只有两个方向…

openCV Cuda

下载 git clone https://github.com/opencv/opencv.git git clone https://github.com/opencv/opencv_contrib.git确保准备好以下内容 1&#xff1a; visual studio &#xff08;不是vs code&#xff09; 2&#xff1a;下载后的两个包裹会放在以下结构 这样放的原因是我Ub…

Java EE-使用Servlet搭建一个简单的前后端交互程序

上述前端和后端的代码如下&#xff1a; 前端&#xff1a; <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta http-equiv"X-UA-Compatible" content"IEedge"><meta name"vie…

数据库笔记——SQL语言DQL语句

schema等于database 数据库 datagrip中使用控制台进行操作&#xff1a; 右键new QueryConsole 创建表格create table中&#xff1a; 1. 括号内不管是定义属性还是声明约束&#xff0c;都使用逗号分隔&#xff0c;最后一句不用逗号 2. 括号外使用分号 DDL&#xff1a;数据库定…

python接口自动化测试(单元测试方法)

一、环境搭建 python unittest requests实现http请求的接口自动化Python的优势&#xff1a;语法简洁优美, 功能强大, 标准库跟第三方库灰常强大&#xff0c;建议大家事先了解一下Python的基础;unittest是python的标准测试库&#xff0c;相比于其他测试框架是python目前使用最广…

思辨:移动开发的未来在哪?

前段时间在知乎看到关于移动开发未来的问题&#xff0c;就尝试回答了一下&#xff0c;也触发了我对移动开发未来的思考。 移动开发未来怎么样? - 知乎 https://www.zhihu.com/question/613842211 什么是移动开发&#xff1f; 我们口中说的移动开发是什么&#xff0c;从广义和…

项目管理实战总结(二)-沟通路径

在一个大型的项目管理中&#xff0c;不同的沟通路径&#xff0c;会对整个事情的进展形成不同的影响。从项目管理的视角来看&#xff0c;该如何驱动项目有效进展&#xff0c;失之毫厘谬以千里。 沟通路径&#xff1a;调查问卷的推动事宜 在项目进行到了后期&#xff0c;甲方希…

项目管理实战总结(一)

前言 主动申请参与到这个项目&#xff0c;是非常清楚工作强度大、难度大的情况的&#xff0c;明知山有虎偏向虎山行。我确信通过这个项目&#xff0c;一定有我需要的东西。目前项目已经完成了终验的专家评审&#xff0c;进入到运维阶段。对于个人而言&#xff0c;如果记忆中只…

全网超细,自动化测试-数据管理/实施落地问题,跟着直接上高速...

目录&#xff1a;导读 前言一、Python编程入门到精通二、接口自动化项目实战三、Web自动化项目实战四、App自动化项目实战五、一线大厂简历六、测试开发DevOps体系七、常用自动化测试工具八、JMeter性能测试九、总结&#xff08;尾部小惊喜&#xff09; 前言 自动化测试——测…

C++迭代器失效

在STL中&#xff0c;有些操作会导致迭代器失效&#xff0c;即之前获取的迭代器无法再安全地使用。这是因为这些操作可能会改变容器的结构&#xff0c;例如插入、删除元素等。 具体来说&#xff0c;以下情况下迭代器会失效&#xff1a; 1. 当插入或删除元素导致容器中的内存重新…

Go并发可视化解释 - sync.WaitGroup

场景 Avito是一名校车司机&#xff0c;他帮助4个Gopher孩子上学。每天&#xff0c;Avito在他们的社区等待孩子们。他不知道孩子们需要多长时间&#xff0c;但他确切地知道有4个孩子他需要等待。 1*aZnEggopv4Tsbyyj3e5JFg.png 当一个孩子准备好时&#xff0c;他/她会说&#xf…

跨境干货 | 如何搭建自己的独立站?

很多跨境电商在第三方平台经营许久后&#xff0c;会想摆脱第三方规则的限制建立起自己的品牌。 对于新手来说建立独立站是很有挑战的&#xff0c;建立独立站前首先我们需要了解一下什么是独立站&#xff1f;从字面意思来理解就是拥有属于自己的网站自己搭建跨境独立站&#xff…

【Python语言速回顾】——基础语法

目录 引入 一、PEP8代码规范和风格 二、变量和数据 1、变量 2、运算符 三、三种程序结构 1、分支结构 2、循环结构 四、组合数据类型 1、列表&#xff08;list&#xff09; 2、元组&#xff08;tuple&#xff09; 3、字典&#xff08;dict&#xff09; 5、集合&…

Python学习基础笔记七十七——json序列化

客户端和服务端之间需要交换数据才能完成各种功能。 假设 服务端程序都是用Python语言开发的话&#xff0c;那么 服务端从数据库中获取的最近的交易列表&#xff0c;可能就是像下面这样的一个Python列表对象&#xff1a; historyTransactions [{time : 20170101070311, #…

LoadRunner录制脚本+编写脚本

LoadRunner安装* 为什么选择LoadRunner 1&#xff09;Jmeter没有录制功能 2&#xff09;可以设计非常非常丰富的测试场景 3&#xff09;LoadRunner能够产出非常丰富的测试报告 LoadRunner三大组件的关系 每个组件是干什么的 VUG&#xff1a;录制脚本&#xff0c;&#xff…