前端 - Vue中的AJAX、VueX、路由


Vue文档

目录
  • AJAX
    • 配置代理
      • 方式一
      • 方式二
  • 插槽
    • 默认插槽
    • 具名插槽
    • 作用域插槽
  • Vuex
    • 环境安装
    • 举例
    • mapState与mapGetters
    • mapActions与mapMutations
    • Vuex模块化
  • 路由
    • 路由简介
      • SPA应用
      • 路由的理解
    • 路由的基本使用
    • 嵌套路由
      • query参数
      • 命名路由
      • params参数
    • props配置
      • 第一种:对象写法
      • 第二种:布尔值写法
      • 第三种:函数写法
    • replace属性
    • 编程式路由导航
    • 缓存路由组件
    • 两个新的生命周期
    • 路由守卫
      • 全局前置路由守卫
      • 全局后置路由守卫
      • 独享路由守卫
      • 组件内路由守卫
    • history模式与hash模式
  • UI组件库
    • 移动端
    • PC端

AJAX

配置代理

官方文档

方式一

服务器:

/* server1.js */
const express = require('express')
const app = express()

app.use((request,response,next)=>{
	console.log('有人请求服务器1了');
	next()
})

app.get('/students',(request,response)=>{
	const students = [
		{id:'001',name:'tom',age:18},
		{id:'002',name:'jerry',age:19},
		{id:'003',name:'tony',age:120},
	]
	response.send(students)
})

app.listen(9000,(err)=>{
	if(!err) console.log('服务器1启动成功了,请求学生信息地址为:http://localhost:9000/students');
})

客户端MyTest.vue:




需要配置代理服务器,端口号和客户端相同:

/* vue.config.js */

const { defineConfig } = require('@vue/cli-service')
module.exports = defineConfig({
  // ...
  devServer: {
    proxy: 'http://localhost:9000'
  }
})

如果在MyTest.vue直接请求http://localhost:9000/students,会出现跨域请求错误:

Access to XMLHttpRequest at 'http://localhost:9000/students' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

点击按钮成功请求,输出以下信息:

请求成功 (3) [{…}, {…}, {…}]

方式二

方式一的两个缺点:

  1. 只能配置一个代理,即只能给http://localhost:9000转发(AJAX请求)
  2. 如果本地有同名文件,则不会走代理,例如存在一个public/students文件,则方式一不会走代理,而是直接拿到本地的文件
sendAjax() {
  axios.get("http://localhost:8080/api/students").then(
    (response) => {
      console.log("请求成功", response.data);
    },
    (error) => {
      console.log("请求失败", error.message);
    }
  );
},
devServer: {
  proxy: {
    '/api': {  // 匹配所有以/api开头的请求路径
      target: 'http://localhost:9000',  // 目标端口
      ws: true, // 用于支持websocket
      changeOrigin: true,
      pathRewrite: {'^/api': ''}
    },
    '/foo': {
      target: 'http://localhost:9001',
      pathRewrite: {'^/foo': ''}
    }
  }
}

以/api为例:

  • 当changeOrigin设置为false,服务器收到的请求头中的host为localhost:8080;设置为true时则为localhost:9000,默认为ture
  • pathRewrite的意思是将请求中的/api变为空串,即http://localhost:8080/api/students变成http://localhost:8080/students

插槽

默认插槽



  

分类

  • 00001
  • 00002
  • 00003
  • 00004
默认插槽,当使用者没有传递具体结构时会出现

具名插槽

多个插槽需要起名:



  

分类

  • 00001
  • 00002
  • 00003
  • 00004
baidu插槽,当使用者没有传递具体结构时会出现 bing插槽,当使用者没有传递具体结构时会出现

当插槽内有多个结构,但是又不希望使用

包裹破坏结构时,可以使用