尝鲜vue3.0- 看完就开干(4)

背景

延续前面的三篇文章:html

距离正式开发还须要介绍一下路由变化,这样就算对vue3.0开发的以有了初步了解,以及完成项目的基础建设。vue


安装vue-router

//目前最新版本
npm i --save vue-router@4.0.0-beta.9
"vue-router": "^4.0.0-beta.9"
//配置
import { createRouter, createWebHashHistory } from 'vue-router'

const router = createRouter({
  //createWebHistory() hostory模式
  history: createWebHashHistory(),//hash模式 
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    // 动态路径参数 以冒号开头
    { path: '/home', component: () => import('../views/home.vue') },
  ],
})
export default router
//使用 main.js
app.use(router)

scoped slot(做用域插槽)

本来是想要 <router-link> 渲染成某种标签,可是使用起来会不够直观清晰git

//以前
//tag="button"  router-link将会渲染成button标签
<router-link to="/" tag="button">
    <Icon>home</Icon><span class="xs-hidden">Home</span>
</router-link>
//以后 使用scoped slot替换
<router-link to="/">
  <button role="link">
    <Icon>home</Icon><span class="xs-hidden">Home</span>
  </button>
</router-link>
  • 删除 event属性(vue2.0 router文档event介绍
    默认是'click',声明能够用来触发导航的事件。能够是一个字符串或是一个包含字符串的数组。也被删除,用做用域插槽代替。
  • 中止自动将点击事件分配给内部锚点
  • 新增scoped-slot API
  • 添加custom prop以彻底自定义router-link的渲染

  • 简写方式(有坑)github

    //从第二篇的地方有介绍过v-slot有简写方式,可是这里值得注意,下方的写法在浏览器渲染却有不通
    <router-link to="/about" #custom="{ href }">
       <a :href="href">1.{{href}}</a>
     </router-link>
     <router-link to="/about" v-slot:custom="{ href }">
       <a :href="href">2.{{href}}</a>
     </router-link>
    
     <router-link to="/about" custom v-slot="{ href }">
       <a :href="href">3.{{href}}</a>
     </router-link>

渲染以后的结果只有第三个正常显示vue-router

---
### vue-router的APInpm

和vue3.0同样,api所有走import,不放在this里面(打印 require('vue-router'))segmentfault


meta属性(给路由附加数据的属性)

{ path: '/my', meta: { requiresAuth: true }}
//以前
router.beforeEach((to, from, next) => {
  if (to.meta.requiresAuth && !auth.loggedIn()) next('/login')
  else next()
})
//建议3.0
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth))
  // ...do sth
})

router-link-active/router-link-exact-active class类名

  • 别名和子路由也将激活
  • params不一致不会被激活

假设当前路由/parent/1/child/2api

url active exact active
/parent/1/child/2
/parent/1/child/3 X X
/parent/1/ X

提供能够在路由运做时增删路由记录的API

//my.vue
import {useRouter,useRoute} from 'vue-router' //见上文介绍的vue-router目前的API
setup(props,ctx){
   console.log(useRouter(window.location.pathname));//相似原来的 this.$router
   console.log(useRoute(window.location.pathname));//相似原来的 this.$route
 }
//路由记录的值
const routeRecord: RouteRecord = {
  path: '/new-route',
  name: 'NewRoute',
  component: NewRoute
}
router.addRoute(route: RouteRecord) //新增一个路由记录
router.removeRoute(name: string | symbol) //删除
router.hasRoute(name: string | symbol)://判断是否存在
router.getRoutes(): RouteRecord[] //获取记录列表

路由跳转

  • 明肯定义路由跳转失败,而后如何捕获错误
  • 路由跳转将是Promise形式
  • 将router.push与router.afterEach,router.onError保持一致数组

    router.push('/dashboard').then((failure) => {
      if (failure) {
        failure instanceof Error // true
        failure.type // NavigationFailure.canceled 【aborted,canceled,duplicated】
      }
    }).catch(()=>{...})

同时使用keep-alive与transition

//之前
<transition :name="transitionName" >
  <keep-alive >
    <router-view></router-view>
    <router-view></router-view>
  </keep-alive>
</transition>
//以后
<router-view v-slot="{ Component }">
  <transition :name="transitionName" mode="out-in">
    <component :is="Component"></component>
  </transition>
</router-view>

滚动行为

不经常使用,vue2.0在官网上的介绍浏览器

//改动不大,只是为了更加贴近原生,将属性名统一了
{ selector:..,x: 0, y: 200,behavior }
// becomes
{ el:...,left: 0, top: 200,offset }

在激活某路由的时候增长逻辑判断,将路由视图显示其余内容(好比一些loading状态)

<router-view :route="routeWithModal"></router-view>
const App = {
  computed: {
    routeWithModal() {
      if (backgroundView) {
        return this.$router.resolve(backgroundView)
      } else {
        return this.$route
      }
    }
  }
}

路由守卫不用使用next,也能够直接返回某个值或者是Promise

// 以前
router.beforeEach((to, from, next) => {
  if (!isAuth) next(false)
  else next()
})

// 之后能够
router.beforeEach(() => isAuth)

最后

安装了解完路由的相关变更,直接能够开干了。整个过程下来,vue3.0的变化仍是能够接受的,在向更好的方向发展。推荐使用vite也很好,不少东西都内置,开箱即用。至于typesciprt,只是vue3.0更好的支持了ts语法,可是用不用,怎么用仍是看项目以及开发者自己。目前介绍vue3.0的使用,到此其实已经能够开始写项目了。还有Vue Composition API没介绍,可是简单和经常使用的API在上面已经用过了,后期再更新。

github代码地址

介绍到这里,有遗漏欢迎你们补充,喜欢的动手收藏点赞。

相关文章
相关标签/搜索