一、网络请求
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