Master the installation and use of vue-router in one article
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.
【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
Step 2: Use it in modular projects (because It is a plug-in, so you can install the routing function through Vue.use())
Import the routing object and call
Vue.use(VueRouter)
Create routing instance and pass in routing mapping configuration
in Vue instancemountcreated routing instance
2. The configuration file of the router created using
is located in index.js# under the
router folder under src. ##The content in the file
Note: Although the router has been registered here, it needs to be hung. It only works on vue.
Mounting method:
Introducerouter 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) })
<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='/home' tag="button" replace>首页</router-link> <router-link to='/about' 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:'yzk' } }, methods: { aboutClick() { // 通过代码的方式修改路由 vue-router // 不能如下操作:此操作会绕过路由进行修改,违背初衷 // history.pushState({},'','home') // 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('/user/'+this.userId); }, profileClick(){ this.$router.push({ path:'/profile', query:{ name:'kobe', age:18, height:1.98 } }) } }, }; </script> <style> .router-link-active { color: red; } .active { color: pink; } </style>
// 配置路由信息 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('----'); })
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) })
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Using ECharts in Vue makes it easy to add data visualization capabilities to your application. Specific steps include: installing ECharts and Vue ECharts packages, introducing ECharts, creating chart components, configuring options, using chart components, making charts responsive to Vue data, adding interactive features, and using advanced usage.

Question: What is the role of export default in Vue? Detailed description: export default defines the default export of the component. When importing, components are automatically imported. Simplify the import process, improve clarity and prevent conflicts. Commonly used for exporting individual components, using both named and default exports, and registering global components.

The Vue.js map function is a built-in higher-order function that creates a new array where each element is the transformed result of each element in the original array. The syntax is map(callbackFn), where callbackFn receives each element in the array as the first argument, optionally the index as the second argument, and returns a value. The map function does not change the original array.

In Vue.js, event is a native JavaScript event triggered by the browser, while $event is a Vue-specific abstract event object used in Vue components. It is generally more convenient to use $event because it is formatted and enhanced to support data binding. Use event when you need to access specific functionality of the native event object.

onMounted is a component mounting life cycle hook in Vue. Its function is to perform initialization operations after the component is mounted to the DOM, such as obtaining references to DOM elements, setting data, sending HTTP requests, registering event listeners, etc. It is only called once when the component is mounted. If you need to perform operations after the component is updated or before it is destroyed, you can use other lifecycle hooks.

There are two ways to export modules in Vue.js: export and export default. export is used to export named entities and requires the use of curly braces; export default is used to export default entities and does not require curly braces. When importing, entities exported by export need to use their names, while entities exported by export default can be used implicitly. It is recommended to use export default for modules that need to be imported multiple times, and use export for modules that are only exported once.

Vue hooks are callback functions that perform actions on specific events or lifecycle stages. They include life cycle hooks (such as beforeCreate, mounted, beforeDestroy), event handling hooks (such as click, input, keydown) and custom hooks. Hooks enhance component control, respond to component life cycles, handle user interactions and improve component reusability. To use hooks, just define the hook function, execute the logic and return an optional value.

Vue.js event modifiers are used to add specific behaviors, including: preventing default behavior (.prevent) stopping event bubbling (.stop) one-time event (.once) capturing event (.capture) passive event listening (.passive) Adaptive modifier (.self)Key modifier (.key)
