Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

vue.js - regex for router links

I'm trying to build a navbar and since it will receive the links from a prop so it might be a router link or hyperlink which is why I want to use regex to check if the first character is / and if so then use push or else use href. however I'm getting one error. what am I doing wrong here? is my regex wrong? also is my approach correct?

error  Unnecessary escape character: /          no-useless-escape

my code so far

<template>
  <nav>
    <ul>
      <li v-for="(item, $index) in navLinks" :key="$index">
        <router-link :to="item.link" v-if="item.link.match(reg)">{{ item.name }}</router-link>
        
        <a :href="item.link" v-else>{{ item.name }}</a>
      </li>
    </ul>
  </nav>
</template>

<script>
export default {
  name: "Navbar",
  props: {
    navLinks: {
      type: Array,
    },
  data () {
  return {
    reg: '^[/].*' // the regex which sees if the first character is `/` or not
    }
   }
   }
</script>

the navlinks can be

const navLinks = [
  { name: "About", 
    link: "#about" },
  {
    name: "Projects",
    link: "/projects",
  },
];
question from:https://stackoverflow.com/questions/65859136/regex-for-router-links

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

In vue, if you want to use a variable in the template section then you need to define it inside the data property.

data () {
  return {
    reg: '^[/].*'
  }
}

Now you can access this reg in the template section.

For the issue of the regular expression, define your regex as '^[/].*'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...