Vue2-8Vuex与Router

本文详细介绍了Vuex在Vue应用中的核心作用,包括store、state、mutation、action和getter的使用,以及如何通过npm和yarn安装和配置Vuex。同时涵盖了Vue Router的路由模式、配置、组件使用和参数传递,以及路由优化和异步加载策略。

Vuex

概述

  1. Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。---- 工具,用于管理应用中组件间共享的状态(数据)
  2. 采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化

概念

  1. store:仓库,用于集中式管理
  2. state:状态,应用中组件要共享的数据
  3. mutation:同步更新状态数据的函数,在 vuex 中仅能提交 mutation 来更新状态数据
  4. action:和 mutation 类似,但可以包含异步操作,不能直接更新状态,而是要提交 mutation 更新
  5. getter:是 store 中的计算属性
  6. module:模块,每个模块可以有自己的 state、mutation、action、getter,甚至自己的 module

使用

  1. 安装
  • npm安装$ npm i vuex@3.6.2
  • yarn安装$ yarn add vuex@3.6.2
  1. 创建 Store
import Vue from 'vue'
import Vuex from 'vuex'

// 使用核心插件 Vuex
Vue.use(Vuex)

// 创建 Store
const store = new Vuex.Store({
  state: { // 组件间共享的数据
    todos: [],
  },
  mutations: { // 唯一进行同步更新状态数据的方法
    /**
     * 添加新待办事项
     */
    addTodoItem(state, payload) {
      state.todos.push({
        id: Math.random(),
        title: payload.title,
        completed: false,
      })
    },
  },
})

export default store

向根实例中注入 store

import Vue from 'vue'

// 引入 store
import store from './store' // import store from './store/index.js'

new Vue({
  store, // 注入 store,这样,在所有后代组件中,都可以使用 this.$store 获取 vuex 的 Store 使用
  // render: h => h(App),
}).$mount('#app')

在组件中使用 store

  1. this.$store.state.todos // 类似于data拿里面数据
  2. this.$store.commit(mutationType, payload) // 类似于触发事件(mutation同步)
  3. this.$store.getters.allChecked // 类似于计算属性
  4. this.$store.dispatch().allChecked // 类似于触发事件(action异步)

辅助函数

store中各自的映射

import { mapState, mapGetters, mapMutations, mapActions } from 'vuex' // 解构出来vuex仓库中保存的数据

Vue Router

SPA

single page application(单页面应用程序),即在整个应用中,只有一个 html 页面,在用户与应用之间实现交互时能够动态更新页面内容。

前端路由

利用 hashhistory 改变不会向后端发起新的 html 请求

模式

  1. hash:利用 URL 中 #hash hash 值改变后,不会发送新的网络请求的特点,来实现的路由。使用如 #/home、#/login 类似的方式来表示所请求的前端 URL 资源
  2. history:利用 h5 中 history 新增的 API pushState()、replaceState() 来实现。其路由的格式与服务端路由 URL 格式一致(比 hash 模式来说,没有多余的如 # 之类的符号),这种路由模式要用好,还需要服务端配置

Vue Router是 Vue.js 官方的路由管理器,是一个核心插件,与 Vue.js 高度集成

  1. path 路径名
  2. component 组件(只有一个是)
  3. components 组件(多个是)
  4. children 子路由
  5. meta 路由信息

安装

  • npm安装$ npm i vue-router@3.5.3
  • yarn安装$ yarn add vue-router@3.5.3

定义 VueRouter 对象

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@/views/Home'
import Login from '@/views/Login'

// 使用路由插件
Vue.use(VueRouter)

// 创建 VueRouter 对象
const router = new VueRouter({
  mode: 'hash', // 路由模式,可取 hash、history,默认为 hash
  routes: [ // 静态路由的配置信息
    {
      path: '/home', // 当 URL 中访问地址为 /home 时
      component: Home, // 拿 Home 组件渲染
    },
    {
      path: '/login',
      component: Login,
    },
  ],
})

// 导出路由对象
export default router

在 Vue 组件中使用 VueRouter 时,可使用 VueRouter 提供的两个内置组件:

  1. router-link:链接,相当于<a>
  2. router-view:视图,用于渲染访问路径所对应的组件
  3. 注入 router 到 vue 根实例
// 引入 router
import router from './router'

new Vue({
  router,
  // render: h => h(App),
}).$mount('#app')
  1. 当在 Vue 根实例中注入了 router 后,在 vue 组件中会自动注入如下两个属性:
  • $router:代表 VueRouter 对象实例
  • $route:代表的是当前激活的路由对象
<template>
  <div class="app">
    <router-link to="/index">首页</router-link>
    <button @click="singinHandle">切换登录</button>
    <router-view />
  </div>
</template>

<script>
export default {
  name: 'App',
  created () {
    this.$watch(
      () => this.$route.params,
      (toParams, previousParams) => {
        console.log(this.$route)
        // 对路由变化做出响应...
      }
    )
  },
  methods: {
    singinHandle () {
      // this.$router.push({
      //   path: '/signin'
      // })
      this.$router.push({
        path: '/singin',
        query: {
          id: 1
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>

</style>

路由传参

  1. ? 查询字符串query
  2. :动态路径参数params
  3. 路由元信息meta
  4. 获取参数
    1. $route.query
    2. $route.params
    3. $route.meta

路由守卫

  1. 全局前置守卫beforeEach((to, from, next)=>{})(任意位置路由导航都会触发)
    1. to:到哪个路由去
    2. from:从哪个路由来
    3. next:下一步(无论失败与否都要执行这个参数,不然会阻塞程序运行)
  2. 路由独享守卫(可以直接在路由配置中写这个函数)
const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {  // Key
        // ...
      }
    }
  ]
})
  1. 组件级
  • beforeRouteEnter进入组件之前
beforeRouteEnter:(to,from,next)=>{
 	alert(this.data);  //此时组件还未实例化 弹出为 unedfind
    next(vm =>{
      alert(vm); //vm相当于this
    })
  }
  • beforeRouteUpdate该组件被复用时调用
	beforeRouteUpdate (to, from, next) {
    // 当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /a/:id,在 /a/1 和 /a/2 之间跳转的时候,
    // 由于会渲染同样的 a组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
  }
  • beforeRouteLeave 离开组件之后
 beforeRouteLeave(to,from,next){
      if(confirm("确定离开吗?") == true){
        next() 
      }else{
        next(false);
      }
  }

路由优化

  1. 路由打包后所有的JS文件都放在一个文件里,这会导致页面首次加载时数据量过大,页面加载缓慢
  2. 解决办法
  • 异步加载
{ path: '/home', name: 'home', component: resolve => require(['@/components/home'],resolve) }
  • 路由懒加载(使用import)
const 组件名=() => import('组件路径');
评论 55
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

鹏程933

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值