Table of Contents
vue-router Installation and use
1. Installation" >1. Installation
2. The configuration file of the router created using " > 2. The configuration file of the router created using
我是app组件
Home Web Front-end Vue.js Master the installation and use of vue-router in one article

Master the installation and use of vue-router in one article

Aug 10, 2022 pm 05:55 PM
vue

This article brings you relevant knowledge about vue, which mainly introduces the relevant knowledge about the installation and use of vue-router. Let’s take a look at it together. I hope it will be helpful to everyone.

Master the installation and use of vue-router in one article

【Related recommendations: javascript video tutorial, vue.js tutorial

vue-router Installation and use

1. Installation

Step 1: Install vue-router

npm install vue-router --save
Copy after login

Step 2: Use it in modular projects (because It is a plug-in, so you can install the routing function through Vue.use())

  1. Import the routing object and call Vue.use(VueRouter)

  2. Create routing instance and pass in routing mapping configuration

  3. in Vue instancemountcreated routing instance


2. The configuration file of the router created using

Master the installation and use of vue-router in one article

is located in index.js# under the router folder under src. ##The content in the file

index.js is as follows:

Master the installation and use of vue-router in one article

Note: Although the router has been registered here, it needs to be hung. It only works on vue.

Mounting method:

Introduce

router in main.js under the src file, and Mounted on the vue instance.

//main.js
import Vue from 'vue'
import App from './App'
import router from './router'


Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render: h => h(App)
})
Copy after login
Actual use case:

The key configuration in App.vue is as follows:

<template>
  <div>
    <h2 id="我是app组件">我是app组件</h2>
    
    <!-- 通过router自带标签实现 -->
    <router-link>首页</router-link>
    <router-link>关于</router-link> 
    <router-link>用户</router-link>
    <router-link>档案</router-link>
    <!-- <router-link to=&#39;/home&#39; tag="button" replace>首页</router-link>
    <router-link to=&#39;/about&#39; tag="button" replace >关于</router-link>-->

    <!-- 通过代码跳转 -->
    <!-- 
    <button @click="homeClick">首页</button>
    <button @click="aboutClick">关于</button> 
    -->
    <keep-alive>
      <router-view></router-view>
    </keep-alive>

    <button>用户2</button>
    <button>档案</button>
  </div>
</template>

<script>
export default {
  name: "App",
  data(){
    return{
      userId:&#39;yzk&#39;
    }
  },
  methods: {
    aboutClick() {
      // 通过代码的方式修改路由 vue-router
      // 不能如下操作:此操作会绕过路由进行修改,违背初衷
      // history.pushState({},&#39;&#39;,&#39;home&#39;)
      // this.$router.push("/home");
      this.$router.replace("/home");
      console.log("about");
    },
    homeClick() {
      // this.$router.push("/about");
      this.$router.replace("/about");
      console.log("home");
    },
    userClick(){
      this.$router.push(&#39;/user/&#39;+this.userId);
    },
    profileClick(){
      this.$router.push({
        path:&#39;/profile&#39;,
        query:{
          name:&#39;kobe&#39;,
          age:18,
          height:1.98
        }
      })
    }
  },
};
</script>

<style>
.router-link-active {
  color: red;
}
.active {
  color: pink;
}
</style>
Copy after login
Router’s index.js file is as follows:

// 配置路由信息
import Vue from 'vue'
import VueRouter from 'vue-router'
// import Home from '../components/Home'
// import About from '../components/About'
// import User from '../components/User'

// 懒加载,提高效率(因为app.js文件中集成了所有的业务代码,因此请求事件可能较长
// 通过将app.js分隔,在需要使用某些js代码的时候,才接收其代码)
const Home = () => import('../components/Home')
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')

const About = () => import('../components/About')
const User = () => import('../components/User')
const Profile = () => import('../components/Profile')



// 1.通过Vue.use(插件),安装插件
Vue.use(VueRouter)

// 2.创建VueRouter对象
const routes = [
  {
    path: '',
    //  component: Home
    // 重定向redirect
    redirect: '/home'
  },
  {
    path: '/home',
    component: Home,
    meta: { title: "首页" },
    children: [
      {
        path: '',
        redirect: 'news'
      },
      {
        path: 'news',
        //  注意这里是没有s的!!!
        component: HomeNews,

      },
      {
        path: 'message',
        component: HomeMessage
      },
    ]
  },
  {
    path: '/about',
    component: About,
    meta: { title: "关于" },
  },
  {
    path: '/user/:userId',
    component: User,
    meta: { title: "用户" },
  },
  {
    path: '/profile',
    component: Profile,
    meta: { title: "档案" },
  }
]
const router = new VueRouter({
  // 配置路由和组件间的映射关系
  routes,
  mode: 'history',
  linkActiveClass: 'active'
})

// 3.将router对象传入到Vue实例中
export default router

// 导航守卫 前置钩子
router.beforeEach((to, from, next) => {
  document.title = to.matched[0].meta.title
  console.log('+++');
  next()
})

// 导航守卫, 后置钩子 不需要调用next函数
router.afterEach((to,from) => {
  console.log('----');
})
Copy after login
main.js Mount in:

import Vue from 'vue'
import App from './App'
import router from './router'


Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render: h => h(App)
})
Copy after login
[Related recommendations:

javascript video tutorial, vue.js tutorial]

The above is the detailed content of Master the installation and use of vue-router in one article. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1668
14
PHP Tutorial
1273
29
C# Tutorial
1256
24
How to use bootstrap in vue How to use bootstrap in vue Apr 07, 2025 pm 11:33 PM

Using Bootstrap in Vue.js is divided into five steps: Install Bootstrap. Import Bootstrap in main.js. Use the Bootstrap component directly in the template. Optional: Custom style. Optional: Use plug-ins.

How to add functions to buttons for vue How to add functions to buttons for vue Apr 08, 2025 am 08:51 AM

You can add a function to the Vue button by binding the button in the HTML template to a method. Define the method and write function logic in the Vue instance.

How to use watch in vue How to use watch in vue Apr 07, 2025 pm 11:36 PM

The watch option in Vue.js allows developers to listen for changes in specific data. When the data changes, watch triggers a callback function to perform update views or other tasks. Its configuration options include immediate, which specifies whether to execute a callback immediately, and deep, which specifies whether to recursively listen to changes to objects or arrays.

How to return to previous page by vue How to return to previous page by vue Apr 07, 2025 pm 11:30 PM

Vue.js has four methods to return to the previous page: $router.go(-1)$router.back() uses &lt;router-link to=&quot;/&quot; component window.history.back(), and the method selection depends on the scene.

What does vue multi-page development mean? What does vue multi-page development mean? Apr 07, 2025 pm 11:57 PM

Vue multi-page development is a way to build applications using the Vue.js framework, where the application is divided into separate pages: Code Maintenance: Splitting the application into multiple pages can make the code easier to manage and maintain. Modularity: Each page can be used as a separate module for easy reuse and replacement. Simple routing: Navigation between pages can be managed through simple routing configuration. SEO Optimization: Each page has its own URL, which helps SEO.

React vs. Vue: Which Framework Does Netflix Use? React vs. Vue: Which Framework Does Netflix Use? Apr 14, 2025 am 12:19 AM

Netflixusesacustomframeworkcalled"Gibbon"builtonReact,notReactorVuedirectly.1)TeamExperience:Choosebasedonfamiliarity.2)ProjectComplexity:Vueforsimplerprojects,Reactforcomplexones.3)CustomizationNeeds:Reactoffersmoreflexibility.4)Ecosystema

How to use vue traversal How to use vue traversal Apr 07, 2025 pm 11:48 PM

There are three common methods for Vue.js to traverse arrays and objects: the v-for directive is used to traverse each element and render templates; the v-bind directive can be used with v-for to dynamically set attribute values ​​for each element; and the .map method can convert array elements into new arrays.

How to reference js file with vue.js How to reference js file with vue.js Apr 07, 2025 pm 11:27 PM

There are three ways to refer to JS files in Vue.js: directly specify the path using the &lt;script&gt; tag;; dynamic import using the mounted() lifecycle hook; and importing through the Vuex state management library.

See all articles