• Vue(3)


    目录

    一、Vue Router?

    安装

    知识点

    1. router-link

    2.router-view

    3. 路由表

     4.创建路由对象

    5.编程式路由

     

    6.路由守卫

     

    使用

    二、Axios异步通信

     1、特性

    2、安装

    3、案例

    4、api

    5.具体属性

    6、响应结构

    7、拦截器

    8.api的封装

     9、跨域请求


    一、Vue Router?

    安装

    npm install vue-router

    知识点

    相当于超链接  to=“”  向当与a标签中的href

    "/login">跳转登录

    2.router-view

    声明路由最终渲染的位置

     

    3. 路由表

    path 定义了请求地址  path=“/”

    name 定义了路由的名称 保证唯一

    component 指定该请求需要对应的视图,放的是组件

    children   内嵌路由

    redirect   路由与路由之间的跳转

    1. {
    2. //转发
    3. path: '/test',
    4. name: 'test',
    5. redirect: '/login'
    6. },
    7. {
    8. //请求路径 ==getMapping
    9. //path必须以/ 开头 ,如果是嵌套路由,子路由不允许
    10. path: "/login",
    11. //路由名称(唯一)
    12. name: "Login",
    13. //路由需要响应的组件
    14. component: () =>
    15. import ('../components/Login.vue'),
    16. children: [{
    17. //嵌套不能有/开头
    18. path: 'main1',
    19. name: 'main1',
    20. component: Main1
    21. },
    22. {
    23. //嵌套不能有/开头
    24. path: 'main2',
    25. name: 'main2',
    26. component: Main2
    27. }
    28. ]
    29. }

     4.创建路由对象

    1. new VueRouter({
    2. })

    5.编程式路由

     

    1. console.info(this.$router)
    2. //不可以回退
    3. this.$router.replace("/login")
    4. //可以回退
    5. // this.$router.push("/login")

    6.路由守卫

     

    1. //导航守卫 如果不写next()是不会进行放行的
    2. router.beforeEach((to, from, next) => {
    3. // console.info("..................当前导航即将离开" + from.path)
    4. // console.info("...................即将进入" + to.path + "这个请求")
    5. // if (to.path == "/login") {
    6. // // 权限验证
    7. // next()
    8. // } else {
    9. // next("/login")
    10. // }
    11. next()
    12. })
    13. // router.afterEach((to,from)=>{
    14. // console.info("after.................."+to.path+";"+from.path)
    15. // })

    使用

    1.创建router文件夹  创建index.js 

    2.导入组件

     注意:组件必须要导入出去

    3.创建路由表和路由对象

    1. //导入 组件 ---前提组件要导出
    2. import HelloWorld from '../components/HelloWorld.vue'
    3. import Login from '../components/Login.vue'
    4. import Main1 from '../components/Main1.vue'
    5. import Main2 from '../components/Main2.vue'
    6. //导入router
    7. import VueRouter from 'vue-router';
    8. //第一步创建路由表
    9. var routes = [{
    10. //请求路径 ==getMapping
    11. //path必须以/ 开头 ,如果是嵌套路由,子路由不允许
    12. // /代表默认选定
    13. path: "/",
    14. //路由名称(唯一)
    15. name: "a",
    16. //路由需要响应的组件
    17. component: HelloWorld
    18. },
    19. {
    20. //请求路径 ==getMapping
    21. //path必须以/ 开头 ,如果是嵌套路由,子路由不允许
    22. path: "/login",
    23. //路由名称(唯一)
    24. name: "Login",
    25. //路由需要响应的组件
    26. component: () =>
    27. import ('../components/Login.vue'),
    28. children: [{
    29. //嵌套不能有/开头
    30. path: 'main1',
    31. name: 'main1',
    32. component: Main1
    33. },
    34. {
    35. //嵌套不能有/开头
    36. path: 'main2',
    37. name: 'main2',
    38. component: Main2
    39. }
    40. ]
    41. },
    42. {
    43. path: '/a/:id',
    44. name: "Login2",
    45. component: HelloWorld
    46. }, {
    47. //转发
    48. path: '/test',
    49. name: 'test',
    50. redirect: '/login'
    51. }
    52. ]
    53. //第二步创建路由对象
    54. var router = new VueRouter({
    55. //属性名:值
    56. //routes:routes 相当于routes 相同的话就可以缩写
    57. routes
    58. })
    59. //导航守卫 如果不写next()是不会进行放行的
    60. router.beforeEach((to, from, next) => {
    61. // console.info("..................当前导航即将离开" + from.path)
    62. // console.info("...................即将进入" + to.path + "这个请求")
    63. // if (to.path == "/login") {
    64. // // 权限验证
    65. // next()
    66. // } else {
    67. // next("/login")
    68. // }
    69. next()
    70. })
    71. // router.afterEach((to,from)=>{
    72. // console.info("after.................."+to.path+";"+from.path)
    73. // })
    74. export default router

    4、在main.js中引入

    1. import Vue from 'vue'
    2. import App from './App.vue'
    3. import router from './router/index.js'
    4. import VueRouter from 'vue-router';
    5. Vue.config.productionTip = false
    6. Vue.use(VueRouter)
    7. //第三步 在实例中绑定路由
    8. new Vue({
    9. render: h => h(App),
    10. router
    11. }).$mount('#app')

    5.在App.vue中使用

    二、Axios异步通信

    Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。他跟jquery的ajax差不多

    官网:起步 | Axios 中文文档 | Axios 中文网

     1、特性

    • 从浏览器中创建 XMLHttpRequests

    • 从 node.js 创建 http 请求

    • 支持 Promise API

    • 拦截请求和响应:既可以拦截请求也可以拦截响应

    • 转换请求数据和响应数据:(请求参数类型以及响应结果类型)

    • 取消请求

    • 自动转换 JSON 数据(json类型)

    • 客户端支持防御 XSRF

    2、安装

    $ npm install axios

    3、案例

    1. // 为给定 ID 的 user 创建请求
    2. // axios对象
    3. // 发送get请求并处理响应结果
    4. axios.get('/user?ID=12345')
    5. // 请求成功执行的方法回调
    6. .then(function (response) {
    7. console.log(response);
    8. })
    9. // 抛出异常时执行的方法
    10. .catch(function (error) {
    11. console.log(error);
    12. });
    13. // 上面的请求也可以这样做
    14. axios.get('/user', {
    15. //简单参数
    16. params: {
    17. ID: 12345
    18. }
    19. })
    20. .then(function (response) {
    21. console.log(response);
    22. })
    23. .catch(function (error) {
    24. console.log(error);
    25. });

    4、api

    config

    • method

    请求方式

    • url

    请求地址

    • data

    请求参数

    • params

    请求参数get

    axios.request(config)

    自定义异步请求,可以通过config.method来设置请求类型 ==$.ajax

    axios.get(url,config)

    发送get异步请求 ==$.get

    axios.delete(url,config)

    发送delete类型的请求 == request config.method='delete'

    axios.head(url[, config])

    axios.options(url[, config])

    axios.post(url[, data[, config]])

    axios.put(url[, data[, config]])

    axios.patch(url[, data[, config]])

    了解即可  ,一般我们后期使用的都是封装的

    5.具体属性

    1. {
    2. // `url` 是用于请求的服务器 URL
    3. url: '/user',
    4. // `method` 是创建请求时使用的方法
    5. method: 'get', // default
    6. // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
    7. // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
    8. baseURL: 'https://some-domain.com/api/',
    9. // `transformRequest` 允许在向服务器发送前,修改请求数据
    10. // 只能用在 'PUT', 'POST' 和 'PATCH' 这几个请求方法
    11. // 后面数组中的函数必须返回一个字符串,或 ArrayBuffer,或 Stream
    12. transformRequest: [function (data, headers) {
    13. // 对 data 进行任意转换处理
    14. return data;
    15. }],
    16. // `transformResponse` 在传递给 then/catch 前,允许修改响应数据
    17. transformResponse: [function (data) {
    18. // 对 data 进行任意转换处理
    19. return data;
    20. }],
    21. // `headers` 是即将被发送的自定义请求头
    22. headers: {'X-Requested-With': 'XMLHttpRequest'},
    23. // `params` 是即将与请求一起发送的 URL 参数
    24. // 必须是一个无格式对象(plain object)或 URLSearchParams 对象
    25. params: {
    26. ID: 12345
    27. },
    28. // `paramsSerializer` 是一个负责 `params` 序列化的函数
    29. // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
    30. paramsSerializer: function(params) {
    31. return Qs.stringify(params, {arrayFormat: 'brackets'})
    32. },
    33. // `data` 是作为请求主体被发送的数据
    34. // 只适用于这些请求方法 'PUT', 'POST', 和 'PATCH'
    35. // 在没有设置 `transformRequest` 时,必须是以下类型之一:
    36. // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
    37. // - 浏览器专属:FormData, File, Blob
    38. // - Node 专属: Stream
    39. data: {
    40. firstName: 'Fred'
    41. },
    42. // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
    43. // 如果请求话费了超过 `timeout` 的时间,请求将被中断
    44. timeout: 1000,
    45. // `withCredentials` 表示跨域请求时是否需要使用凭证
    46. withCredentials: false, // default
    47. // `adapter` 允许自定义处理请求,以使测试更轻松
    48. // 返回一个 promise 并应用一个有效的响应 (查阅 [response docs](#response-api)).
    49. adapter: function (config) {
    50. /* ... */
    51. },
    52. // `auth` 表示应该使用 HTTP 基础验证,并提供凭据
    53. // 这将设置一个 `Authorization` 头,覆写掉现有的任意使用 `headers` 设置的自定义 `Authorization`头
    54. auth: {
    55. username: 'janedoe',
    56. password: 's00pers3cret'
    57. },
    58. // `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
    59. responseType: 'json', // default
    60. // `responseEncoding` indicates encoding to use for decoding responses
    61. // Note: Ignored for `responseType` of 'stream' or client-side requests
    62. responseEncoding: 'utf8', // default
    63. // `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
    64. xsrfCookieName: 'XSRF-TOKEN', // default
    65. // `xsrfHeaderName` is the name of the http header that carries the xsrf token value
    66. xsrfHeaderName: 'X-XSRF-TOKEN', // default
    67. // `onUploadProgress` 允许为上传处理进度事件
    68. onUploadProgress: function (progressEvent) {
    69. // Do whatever you want with the native progress event
    70. },
    71. // `onDownloadProgress` 允许为下载处理进度事件
    72. onDownloadProgress: function (progressEvent) {
    73. // 对原生进度事件的处理
    74. },
    75. // `maxContentLength` 定义允许的响应内容的最大尺寸
    76. maxContentLength: 2000,
    77. // `validateStatus` 定义对于给定的HTTP 响应状态码是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),promise 将被 resolve; 否则,promise 将被 rejecte
    78. validateStatus: function (status) {
    79. return status >= 200 && status < 300; // default
    80. },
    81. // `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
    82. // 如果设置为0,将不会 follow 任何重定向
    83. maxRedirects: 5, // default
    84. // `socketPath` defines a UNIX Socket to be used in node.js.
    85. // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
    86. // Only either `socketPath` or `proxy` can be specified.
    87. // If both are specified, `socketPath` is used.
    88. socketPath: null, // default
    89. // `httpAgent` 和 `httpsAgent` 分别在 node.js 中用于定义在执行 http 和 https 时使用的自定义代理。允许像这样配置选项:
    90. // `keepAlive` 默认没有启用
    91. httpAgent: new http.Agent({ keepAlive: true }),
    92. httpsAgent: new https.Agent({ keepAlive: true }),
    93. // 'proxy' 定义代理服务器的主机名称和端口
    94. // `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
    95. // 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
    96. proxy: {
    97. host: '127.0.0.1',
    98. port: 9000,
    99. auth: {
    100. username: 'mikeymike',
    101. password: 'rapunz3l'
    102. }
    103. },
    104. // `cancelToken` 指定用于取消请求的 cancel token
    105. // (查看后面的 Cancellation 这节了解更多)
    106. cancelToken: new CancelToken(function (cancel) {
    107. })
    108. }

    6、响应结构

    1. {
    2. // `data` 由服务器提供的响应
    3. data: {},
    4. // `status` 来自服务器响应的 HTTP 状态码
    5. status: 200,
    6. // `statusText` 来自服务器响应的 HTTP 状态信息
    7. statusText: 'OK',
    8. // `headers` 服务器响应的头
    9. headers: {},
    10. // `config` 是为请求提供的配置信息
    11. config: {},
    12. // 'request'
    13. // `request` is the request that generated this response
    14. // It is the last ClientRequest instance in node.js (in redirects)
    15. // and an XMLHttpRequest instance the browser
    16. request: {}
    17. }

    7、拦截器

    1. // 添加请求拦截器
    2. axios.interceptors.request.use(function(config) {
    3. // 在发送请求之前做些什么
    4. return config;
    5. }, function(error) {
    6. // 对请求错误做些什么
    7. return Promise.reject(error);
    8. });
    9. // 添加响应拦截器
    10. axios.interceptors.response.use(function(response) {
    11. // 对响应数据做点什么
    12. return response.data;
    13. }, function(error) {
    14. // 对响应错误做点什么
    15. return Promise.reject(error);
    16. });

    8.api的封装

    1. import axios from 'axios';
    2. import qs from 'qs';
    3. // var baseURL = "http://localhost"
    4. // var baseURL = ""
    5. export const get = function(url) {
    6. return axios({
    7. method: 'get',
    8. url,
    9. params: {
    10. "name": 'ada'
    11. }
    12. // baseURL
    13. })
    14. }
    15. export const post = function(url, data) {
    16. return axios({
    17. method: 'get',
    18. url,
    19. //qs.stringify(data) 是序列化进行
    20. data: qs.stringify(data)
    21. })
    22. }
    23. // 添加请求拦截器
    24. axios.interceptors.request.use(function(config) {
    25. // 在发送请求之前做些什么
    26. return config;
    27. }, function(error) {
    28. // 对请求错误做些什么
    29. return Promise.reject(error);
    30. });
    31. // 添加响应拦截器
    32. axios.interceptors.response.use(function(response) {
    33. // 对响应数据做点什么
    34. return response.data;
    35. }, function(error) {
    36. // 对响应错误做点什么
    37. return Promise.reject(error);
    38. });
    • 将封装的方法通过js prototype原型封装到VUE

    • 这样在app.vue中就可以直接使用this.了

     

    1. import Vue from 'vue'
    2. import App from './App.vue'
    3. import router from './router/index.js'
    4. import VueRouter from 'vue-router';
    5. import store from "./store/index.js"
    6. Vue.config.productionTip = false
    7. // import ElementUI from 'element-ui';
    8. // import 'element-ui/lib/theme-chalk/index.css';
    9. Vue.use(VueRouter)
    10. // Vue.use(ElementUI);
    11. import {get } from "./api/index.js"
    12. //设置
    13. Vue.prototype.get = get
    14. //第三步 在实例中绑定路由
    15. new Vue({
    16. render: h => h(App),
    17. router,
    18. store
    19. }).$mount('#app')

    像这样

     9、跨域请求

    因为我们再8080为端口的项目中去访问另外一个端口为80的项目来获取数据,默认我们的请求是不允许被别的请求直接访问。

    • 后端请求中允许跨域

    1. @CrossOrigin

    允许请求跨域访问

    2.设置配置类

    1. package com.sofwin.configer;
    2. import org.springframework.context.annotation.Bean;
    3. import org.springframework.context.annotation.Configuration;
    4. import org.springframework.web.cors.CorsConfiguration;
    5. import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    6. import org.springframework.web.filter.CorsFilter;
    7. /**
    8. * @packageName: com.sofwin.configer
    9. * @author: 温涛
    10. */
    11. @Configuration
    12. public class CrosConfiger {
    13. @Bean
    14. public CorsFilter corsFilter(){
    15. CorsConfiguration corsConfiguration = new CorsConfiguration();
    16. corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
    17. corsConfiguration.addAllowedHeader("*"); // 2 设置访问源请求头
    18. corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
    19. UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    20. source.registerCorsConfiguration("/**", corsConfiguration); // 4 对接口配置跨域设置
    21. return new CorsFilter(source);
    22. }
    23. }

    3.nodejs中代理访问后端服务

    这样的话url就不需要写太多了

    名字一定要叫vue.config.js 

    1. const { defineConfig } = require('@vue/cli-service')
    2. let proxyObj = {}
    3. proxyObj['/'] = {
    4. ws: false,
    5. target: 'http://localhost:80',
    6. // 将前段项目映射到target
    7. changeOrgin: true,
    8. pathRewrite: {
    9. '^/': '/'
    10. }
    11. }
    12. module.exports = defineConfig({
    13. transpileDependencies: true,
    14. //关闭语法检查
    15. lintOnSave: false,
    16. devServer: {
    17. host: 'localhost',
    18. port: '8080',
    19. https: false,
    20. proxy: {
    21. "/": {
    22. target: 'http://localhost:80/',
    23. ws: false,
    24. changeOrgin: true,
    25. pathRewrite: {
    26. '^/': '/'
    27. }
    28. }
    29. }
    30. }
    31. })

    整个项目的代码在gitee上

  • 相关阅读:
    RE:从 0 开始的幼儿园数论生活
    卷积神经网络之卷积层理解(持续更新)
    Docker Swarm 快速入门
    基于单片机的智能交通灯系统的设计
    嵌入式Linux(树莓派)环境设置和交叉编译
    数据库——事务
    01. 信息搜集:Web 1~10
    供给侧结构性改革语境应对世界市场 国稻种芯百团计划行动
    图片加载失败后,怎样让那个图标不显示呢?
    工业交换机选购标准,你知道多少?
  • 原文地址:https://blog.csdn.net/weixin_52574640/article/details/126700386