Vue中router和axios使用教程

响应粉丝要求,出一期router和axios使用教程

目录

响应粉丝要求,出一期router和axios使用教程

一、什么是router

简介

路由模式

二、Vue中的router

安装

配置

使用

三、基本路由配置

定义路由

绑定组件

显示路由链接

四、动态路由匹配

定义动态路由

获取参数

五、嵌套路由

父子路由

命名视图

六、路由导航

编程式导航

带参数导航

导航守卫

七、懒加载路由

懒加载方式

实现方式

八、什么是axios

简介

特点

九、Axios的使用方法

安装

发送请求

响应处理

错误处理


一、什么是router

简介

router是前端路由的一种实现方式,它可以根据不同的URL地址展示不同的页面内容,实现单页应用(SPA)的效果。在Vue框架中,我们可以使用Vue Router来进行路由管理。

路由模式

常见的两种路由模式有:Hash模式和History模式。

  • Hash模式:使用URL中的hash值来表示当前路由状态,当hash发生变化时,页面不会重新加载。
  • History模式:使用浏览器提供的History API来实现路由切换,URL中不再需要hash值,而是使用自然的URL路径来表示当前路由状态,并且在URL中会出现真正的URL地址,但是需要后端服务器支持。

二、Vue中的router

安装

使用npm安装:

npm install vue-router  --save
 //最好加上--save,保存
cnpm install vue-router  --save
//使用cnpm,使用国内镜像下载速度快

配置

在Vue项目中,我们需要在main.js中配置路由信息:

import Vue from 'vue'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/more',
    name: 'more',
    component: more
  }
]

const router = new VueRouter({
  mode: 'history', // 路由模式
  base: process.env.BASE_URL,
  routes
})

new Vue({
  router,
  render: h => h(App),
}).$mount('#app')

使用

在Vue组件中,我们可以使用标签来定义路由链接:

<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/more">More</router-link>
    <router-view></router-view>
  </div>
</template>

其中,to属性表示目标路由地址。

三、基本路由配置

定义路由

在路由配置对象中,我们可以定义路由信息,如下所示:

const routes = [
  {
    path: '/',//斜杠表示再路由时找不到路径时,都会访问到home组件
    name: 'home',
    component: Home
  },
  {
    path: '/more',
    name: 'more',
    component: More
  }
]

其中,path属性表示路由路径,name属性表示路由名称,component属性表示路由对应的组件。

绑定组件

在Vue组件中,我们可以使用标签来展示当前路由对应的组件:

<template>
  <div>
    <router-view></router-view>
  </div>
</template>

显示路由链接

在Vue组件中,我们可以使用标签来定义路由链接:

<template>
  <div>
    <router-link to="/">Home</router-link>
    <router-link to="/more">More</router-link>
  </div>
</template>

其中,to属性表示目标路由地址。

四、动态路由匹配

定义动态路由

在路由配置对象中,我们可以使用冒号+变量名的方式来定义动态路由:

const routes = [
  {
    path: '/user/:id',//id表示动态参数,前面用:
    name: 'user',
    component: User
  }
]

其中,:id表示动态参数。

获取参数

在组件中,我们可以使用$route.params来获取动态参数:

mounted() {
  console.log(this.$route.params.id)
}

五、嵌套路由

父子路由

在路由配置对象中,我们可以为某个路由配置子路由:

const routes = [
  {
    path: '/user/:id',
    name: 'user',
    component: User,
    children: [
      {
        path: 'profile',
        name: 'profile',
        component: UserProfile
      },
      {
        path: 'posts',
        name: 'posts',
        component: UserPosts
      }
    ]
  }
]

命名视图

在组件中,我们可以使用标签来展示命名视图:

<template>
  <div>
    <router-view name="header"></router-view>
    <router-view></router-view>
    <router-view name="footer"></router-view>
  </div>
</template>

在路由配置对象中,我们可以为某个路由配置命名视图:

const routes = [
  {
    path: '/',
    components: {
      default: Home,
      header: Header,
      footer: Footer
    }
  }
]

其中,components属性表示命名视图的组件。

六、路由导航

编程式导航

在Vue组件中,我们可以使用this.$router.push方法进行编程式导航:

methods: {
  goHome() {
    this.$router.push('/')
  }
}

带参数导航

在Vue组件中,我们可以使用this.$router.push方法进行带参数的导航:

methods: {
  goUser(id) {
    this.$router.push({ name: 'user', params: { id } })
  }
}

导航守卫

在Vue Router中,我们可以使用导航守卫来控制路由跳转的行为。常见的导航守卫有:beforeEach、beforeResolve和afterEach。

router.beforeEach((to, from, next) => {
  // to: 目标路由对象
  // from: 来源路由对象
  // next: 控制路由跳转的函数,必须调用
  if (to.name === 'user' && !isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

其中,isAuthenticated表示用户是否已经登录。

七、懒加载路由

懒加载方式

在Vue Router中,我们可以使用懒加载的方式来异步加载组件。懒加载可以优化应用程序的性能,因为它只在需要时才加载组件。

const routes = [
  {
    path: '/more',
    name: 'more',
    component: () => import('./views/More.vue')
  }
]

实现方式

懒加载的实现方式有两种:

  • 使用import函数
  • 使用异步组件

使用import函数的方式示例代码:

const About = () => import('./views/About.vue')

const routes = [
  {
    path: '/more',
    name: 'more',
    component: More
  }
]

使用异步组件的方式示例代码:

const routes = [
  {
    path: '/more',
    name: 'more',
    component: resolve => require(['./views/More.vue'], resolve)
  }
]

八、什么是axios

简介

Axios是一个基于Promise的HTTP客户端,可以用于浏览器和Node.js环境中发送HTTP请求。它具有以下特点:

  • 支持所有常见的HTTP请求方法
  • 支持Promise API
  • 具有自动转换JSON数据的功能
  • 能够取消请求
  • 具有拦截器

特点

Axios的特点如下:

  • 简单易用
  • 配置灵活
  • 支持跨域请求
  • 自动处理响应数据
  • 提供了拦截器,可以对请求和响应进行处理
  • 支持取消请求

九、Axios的使用方法

安装

使用npm安装:

npm install axios  --save//与安装router类似

cnpm install axios  --save//同样推荐使用国内镜像

发送请求

在Vue组件中,我们可以使用axios来发送HTTP请求:

import axios from 'axios'

axios.get('/api/user')
  .then(response => {
    console.log(response.data)
  })
  .catch(error => {
    console.log(error)
  })

其中,get方法表示发送GET请求。

响应处理

在Vue组件中,我们可以使用axios来处理HTTP响应:

import axios from 'axios'

axios.get('/api/user')
  .then(response => {
    console.log(response.data)
  })
  .catch(error => {

     console.log(error)
  })
  .finally(() => {
    // 不管请求成功或者失败都会执行
  })

其中,response.data表示响应数据。

错误处理

在Vue组件中,我们可以使用axios来处理HTTP错误:

import axios from 'axios'

axios.get('/api/user')
  .then(response => {
    console.log(response.data)
  })
  .catch(error => {
    if (error.response) {
      // 服务器返回错误状态码
      console.log(error.response.status)
    } else if (error.request) {
      // 请求发出但没有收到响应
      console.log(error.request)
    } else {
      // 发生了一些其它错误
      console.log('Error', error.message)
    }
  })

其中,error.response表示服务器返回的错误信息,error.request表示请求信息。

关注点赞不迷路!!!

关注点赞不迷路!!!

关注点赞不迷路!!!

猜你喜欢

转载自blog.csdn.net/weixin_59367964/article/details/130160048