It is very simple to use routing to jump and switch pages in Vue. Vue Router is the official routing manager of Vue.js, which can help us implement page switching and navigation in Vue applications. This article will use specific code examples to introduce how to use Vue Router to achieve page jumps and switching.
First, we need to install Vue Router. Vue Router can be installed through npm or yarn.
npm install vue-router
or
yarn add vue-router
After the installation is complete, introduce Vue Router where you need to use it.
import Vue from 'vue' import VueRouter from 'vue-router' Vue.use(VueRouter)
Next, we need to create a VueRouter instance and configure routing. We can create a routing configuration in a separate file and then import and use this routing configuration in the main file.
// router.js import Vue from 'vue' import VueRouter from 'vue-router' import Home from './components/Home.vue' import About from './components/About.vue' import Contact from './components/Contact.vue' Vue.use(VueRouter) const router = new VueRouter({ routes: [ { path: '/', component: Home }, { path: '/about', component: About }, { path: '/contact', component: Contact } ], mode: 'history' // 可选,使用history模式可以去掉URL中的# }) export default router
In the above code, we define three routes: '/' corresponds to the Home component, '/about' corresponds to the About component, and '/contact' corresponds to the Contact component. In addition, we can also set the routing mode through the mode option. The default is hash mode. Use history mode to remove the # in the URL.
Then, introduce and use this routing configuration in the main file.
// main.js import Vue from 'vue' import App from './App.vue' import router from './router' new Vue({ router, // 将路由配置注入Vue实例 render: h => h(App) }).$mount('#app')
In the above code, we inject the routing configuration into the Vue instance so that the routing function can be used throughout the application.
Next, we can use the
Home
Go to About Go to Contact
In the above code, we use the
Finally, we can use the
In the above code, the
So far, we have completed the use of routing to achieve page jumps and switching in Vue. Run the application and you will find that after clicking the
The above is the basic process of using Vue Router to achieve page jumps and switching. By introducing Vue Router, configuring routing, and using the
The above is the detailed content of How to use routing to implement page jumps and switching in Vue. For more information, please follow other related articles on the PHP Chinese website!