Vue小白教程:路由配置(一)配置+动态路由传参

本文是Vue小白教程的第一部分,详细介绍了如何配置Vue路由,包括安装、引入VueRouter、配置路由、挂载以及实现动态路由传参。在配置过程中,通过main.js文件设置根组件和子组件(Home、News),并在模板中添加路由跳转。通过实例展示,当点击‘首页’或‘新闻’时,页面会跳转到相应页面,并能根据动态链接生成不同的页面URL。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

配置过程

1.安装

npm install vue-router --save /cnpm install vue-router --save

2、引入并 Vue.use(VueRouter) (main.js)

import VueRouter from 'vue-router'
Vue.use(VueRouter)

3、配置路由

1、创建组件 引入组件
2、定义路由  (建议复制)
	const routes = [
		{ path: '/foo', component: Foo },
		{ path: '/bar', component: Bar },
		  /*动态路由
		  1、路径参数以冒号开头;
		  2、在对应的页面
  			 this.$route.params获取动态路由的值*/
		{ path: '/content/:aid', component: Content }, 
		{ path: '*', redirect: '/home' }   /*默认跳转路由*/
	]
3、实例化VueRouter
	const router = new VueRouter({
		  routes // (缩写)相当于 routes: routes
	})

4、挂载

new Vue({
	 el: '#app',
	 router,
	 render: h => h(App)
})

5 、根组件的模板里面放上这句话
6、路由跳转

<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>

配置文件main.js

import Vue from 'vue';
import App from './App.vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

//1.创建组件
import Home from './components/Home.vue';
import News from './components/News.vue';
import Content from './components/Content.vue';
import Pcontent from './components/Pcontent.vue';

//2.配置路由   注意:名字
const routes = [
  {
    path: '/home', component: Home },
  {
    path: '/news', component: News },
  {
    path: '/content/:aid', component: Content },   /*动态路由*/
  {
    path: '/pcontent', component: Pcontent },
  {
    path: 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值