Vue周边工具之Vuex、vue-router

158 阅读3分钟

一、Vuex

Vuex是一个专门为Vue.js开发的状态管理库,它可以集中管理Vue.js应用中的所有组件的状态,并提供了一些工具和规则来保证状态变更的可追踪性和可维护性。Vuex的核心概念包括状态(State)、变更(Mutations)、行动(Actions)、获取(Getters)和模块(Modules)。

状态(State)是指应用程序中的数据,可以被多个组件共享。变更(Mutations)是用于修改状态的方法,它们必须是同步的。行动(Actions)是用于提交异步操作的方法,可以包含任意异步操作,包括网络请求等。获取(Getters)是用于获取状态的计算属性。模块(Modules)是用于将应用程序状态分解成多个模块的机制,每个模块都有自己的状态、变更、行动和获取器。

使用Vuex可以方便地管理应用程序中的状态,避免了状态分散和混乱的问题,同时也提高了代码的可维护性和可扩展性。

:只有在Actions里才能执行异步。

Vuex工作流程图:

image.png

二、vue-router

使用Vue Router可以方便地实现单页面应用程序的路由管理,使得应用程序的URL更加友好和可读,同时也提高了应用程序的性能和用户体验。Vue Router还提供了丰富的API和功能,比如动态路由、嵌套路由、命名路由、路由传参、路由懒加载等,可以满足各种复杂的路由场景。

Vue Router 是 Vue.js 官方的路由管理器,它和 Vue.js 核心深度集成,可以非常方便地实现单页应用程序(SPA)的路由功能。Vue Router 提供了多种路由方式,包括 hash 模式、history 模式、嵌套路由、命名路由、路由组件传参等,下面分别介绍一下。

1. hash 模式

hash 模式是 Vue Router 的默认路由模式,它基于 URL 的 hash(#)部分实现,通过监听 hash 的变化来实现路由切换。在 hash 模式下,URL 中的 hash 部分不会被包含在 HTTP 请求中,因此对于服务器来说,只需要处理 URL 的主体部分就可以了,不需要额外的配置。使用 hash 模式的示例如下:

const router = new VueRouter({
  mode: 'hash',
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/contact', component: Contact }
  ]
});

2. history 模式

history 模式是基于 HTML5 History API 实现的路由模式,它通过修改浏览器的 URL 来实现路由切换。在 history 模式下,URL 中不再需要 hash,因此可以更加美观。但是,使用 history 模式需要在服务器端进行额外的配置,以避免在刷新页面时出现 404 错误。使用 history 模式的示例如下:

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/about', component: About },
    { path: '/contact', component: Contact }
  ]
});

3. 嵌套路由

嵌套路由是指在一个路由下面再定义子路由,通过这种方式可以实现更加复杂的路由结构。在 Vue Router 中,嵌套路由的定义方式和普通路由一样,只需要在 routes 数组中定义子路由即可。使用嵌套路由的示例如下:

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Home,
      children: [
        { path: '', component: HomeIndex },
        { path: 'news', component: HomeNews },
        { path: 'about', component: HomeAbout }
      ]
    },
    { path: '/about', component: About },
    { path: '/contact', component: Contact }
  ]
});

4. 命名路由

命名路由是指给路由定义一个名称,通过名称来进行路由跳转。在 Vue Router 中,可以使用 name 属性来定义命名路由,使用 $router.push({ name: 'xxx' }) 来进行跳转。使用命名路由的示例如下:

const router = new VueRouter({
  routes: [
    { path: '/', component: Home, name: 'home' },
    { path: '/about', component: About, name: 'about' },
    { path: '/contact', component: Contact, name: 'contact' }
  ]
});

// 跳转到命名路由
this.$router.push({ name: 'home' });

5. 路由组件传参

路由组件传参是指在路由跳转时传递一些参数给路由组件,让路由组件根据这些参数进行相应的操作。在 Vue Router 中,可以使用 props 属性来传递参数,也可以使用路由参数(即 URL 中的参数)来传递参数。使用路由组件传参的示例如下:

const router = new VueRouter({
  routes: [
    { path: '/', component: Home },
    { path: '/about/:id', component: About, props: true }
  ]
});

// 通过 URL 参数传递参数
this.$router.push({ path: '/about', params: { id: 1 } });

// 通过 props 属性传递参数
<router-link to="/about" :props="{ id: 1 }">About</router-link>