vue-router参数

一、通过路由name属性给导航传参

红色字体为增改内容!!!

1、新建src/router.js

2、src/main.js  

//导入vue和新建的router.js   
import Vue from 'vue'
import router from './router.js'

3、src/router.js

//导入vue和vue-router
import Vue from 'vue'
import VueRouter from 'vue-router'
 
//使用vue-router(名称为VueRouter,可以随便取)
Vue.use(VueRouter)
 
//定义组件模板内容
const first = {template:'<div>这是first内容</div>'}
const second = {template:'<div>这是second内容</div>'}
const Home = {template:'<div>这是Home内容</div>'}
 
const firstFirst = {template:'<div>这是firstFirst内容</div>'}
const firstSecond = {template:'<div>这是firstSecond内容</div>'}
const sld={
template:`
<div class="sld">
<h2>二级组件</h2>
<router-view class="abc"></router-view>
</div>
`
}
//定义组件路径
const router = new VueRouter({
mode:"history",
base:__dirname,
routes:[          //routes
{path:"/", name:"Home",component:Home},
{path:"/first",component:sld,
children:[
{path:"/", name:"Home-first",component:first},
{path:"first", name:"Home-first-first",component:firstFirst},
{path:"second", name:"Home-first-second",component:firstSecond}
]
},
{path:"/second", name:"Home-second",component:second}
]
})
 
//使用组件
new Vue({
router,
template:`
<div id="r">
<p>{{$route.name}}</p>
<ul>
               //router-link to=“指向的组件路径”
<li><router-link to="/">/</router-link></li>                 
<li><router-link to="/first">first</router-link>
<ul>
<li><router-link to="/first/first">first</router-link></li>
<li><router-link to="/first/second">second</router-link></li>
</ul>
</li>
<li><router-link to="/second">second</router-link></li>
</ul>
<router-view class="abc"></router-view>          
       //router-view组件显示区域
</div>
`
}).$mount("#app")        //组件挂载(index.html中定义的div的id为app)
 

4、运行npm run dev,页面显示效果为


二、router-link to给子模版组件里传参

红色框为增改内容!!!

const firstFirst = {template:'<div>这是firstFirst内容 {{ $route.params.id }} </div>'}
const firstSecond = {template:'<div>这是firstSecond内容 {{ $route.params.id }}</div>'}
<li><router-link :to="{name:'Home-first-first',params:{id:111111}}">first</router-link></li>
<li><router-link :to="{name:'Home-first-second',params:{id:222222}}">second</router-link></li>

猜你喜欢

转载自www.cnblogs.com/yijisi/p/11247871.html