Uso de la ruta a la expresión regular y los informes de errores relacionados en vue3+vite

Prefacio:

       path-to-regexp  La función de este método es convertir una cadena en una expresión regular. Generalmente, usamos esto cuando usamos enrutamiento de coincidencia dinámica.

1. Introduzca la ruta a la expresión regular, haga clic en mí para ver más

rutaHaciaRegexp()

pathToRegexp('/foo/:bar')
打印结果:
/^/foo/((?:[^/]+?))(?:/(?=$))?$/i

ejecutivo()

Función: haga coincidir si la dirección URL coincide con la regla.

analizar gramaticalmente()

Función: analiza la parte del parámetro (: id) en la cadena de URL.

compilar()

Función: Rellene rápidamente el valor del parámetro de la cadena de URL.

var pathToRegexp = require('path-to-regexp')

var url = '/user/:id/:name'
var data = {id: 10001, name: 'bob'}
console.log(pathToRegexp.compile(url)(data))
打印结果:
/user/10001/bob

2. Use la ruta a la expresión regular para informar errores y resolver la situación

Error:

 

Solución

import pathToRegexp from 'path-to-regexp' se cambia a:
import * as pathToRegexp from 'path-to-regexp'

 3. Vuelva a empaquetar los componentes relacionados en vue3+vite

Código fuente de Vue2:

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span v-if="item.redirect==='noRedirect'||index==levelList.length-1" class="no-redirect"><i :class="item.meta.icon"></i><span style="margin-left:5px;">{
   
   { item.meta.title }}</span></span>
        <span v-else><i :class="item.meta.icon"></i><a @click.prevent="handleLink(item)" style="margin-left:5px;">{
   
   { item.meta.title }}</a></span>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
// import pathToRegexp from 'path-to-regexp'

export default {
  data() {
    return {
      levelList: null
    }
  },
  watch: {
    $route(route) {
      if (route.path.startsWith('/redirect/')) {
        return
      }
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      let matched = this.$route.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]

      if (!this.isDashboard(first)) {
      }

      this.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
    },
    isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
    },
    pathCompile(path) {
      const { params } = this.$route
      //pathToRegexp 把字符串转为正则表达式
      //pathToRegexp.compile() 快速填充 url 字符串的参数值
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    },
    handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(this.pathCompile(path))
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>

El último código fuente de vue3:

<template>
  <el-breadcrumb class="app-breadcrumb" separator="/">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="(item,index) in levelList" :key="item.path">
        <span v-if="item.redirect==='noRedirect'||index==levelList.length-1" class="no-redirect"><i :class="item.meta.icon"></i><span style="margin-left:5px;">{
   
   { item.meta.title }}</span></span>
        <span v-else><i :class="item.meta.icon"></i><a @click.prevent="handleLink(item)" style="margin-left:5px;">{
   
   { item.meta.title }}</a></span>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
import * as pathToRegexp from 'path-to-regexp'
import {
  reactive,
  watch,
  toRefs,
  getCurrentInstance,
  onMounted
} from 'vue'
export default {
  setup(){
    /************************ hx-定义数据data(START) ************************/
    const data = reactive({
      levelList: null
    })
    /************************ hx-定义数据data(END) ************************/

    /************************ hx-生命周期(START) ************************/
    const { proxy } = getCurrentInstance()

    onMounted(() => {
      getBreadcrumb()
    })
    const router = useRouter()
    watch(() => router.currentRoute.value.path,(toPath) => {
      //要执行的方法
      if (toPath.startsWith('/redirect/')) {
        return
      }
      getBreadcrumb()

    },{immediate: true,deep: true})
    /************************ hx-生命周期(END) ************************/

    /************************ hx-methods(START) ************************/
    function getBreadcrumb() {
      let matched = router.matched.filter(item => item.meta && item.meta.title)
      const first = matched[0]

      if (!isDashboard(first)) {}

      data.levelList = matched.filter(item => item.meta && item.meta.title && item.meta.breadcrumb !== false)
    }
    function isDashboard(route) {
      const name = route && route.name
      if (!name) {
        return false
      }
      return name.trim().toLocaleLowerCase() === 'Dashboard'.toLocaleLowerCase()
    }
    function pathCompile(path) {
      const { params } = route
      debugger
      //pathToRegexp 把字符串转为正则表达式
      //pathToRegexp.compile() 快速填充 url 字符串的参数值
      var toPath = pathToRegexp.compile(path)
      return toPath(params)
    }
    function handleLink(item) {
      const { redirect, path } = item
      if (redirect) {
        router.push(redirect)
        return
      }
      router.push(pathCompile(path))
    }

    /************************ hx-methods(END) ************************/


    return {
      //数据
      ...toRefs(data),
      //methods
      handleLink
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;

  .no-redirect {
    color: #97a8be;
    cursor: text;
  }
}
</style>

Supongo que te gusta

Origin blog.csdn.net/qq_41619796/article/details/128288948
Recomendado
Clasificación