- 使用
$route
- 使用
props
将组件与路由解耦
方式一:使用$route
此方法传递参数不在URL路径拼接显示
这里的路由传递,需要指定路由的名称,若只有路径,会报错,必须指定路由的名称;
//路由 index.js
new Router({
routes: [
{
path: '/orderDetail',
name: 'orderDetail',
component: resolve => require(['@/components/order-detail'], resolve)
}
]
})
//参数传递方
export default {
methods:{
submitOrder(){
this.$router.push({
name: 'orderDetail',
params: {
'order': this.selectedGear
}
})
}
}
}
//参数接收方
export default {
mounted() {
console.log(this.$route.params.order);
}
}
但是此方法会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。
方式二:使用 props
将组件与路由解耦
此方法传递参数会在URL路径拼接显示
//路由 index.js
new Router({
routes: [
{
path: '/content/:id',
component: content,
props:true
}
]
})
//参数传递方 此处的number值即为参数id的值
<router-link :to="'/content/'+number" class="blog-list">阅读全文</router-link>
//参数接收方 重点:props
<script>
export default {
props: ['id'],
data () {
return {
data: '',
url: 'blog/article/'
}
},
mounted () {
this.$http.get(this.url + this.id).then(res => {
this.data = res
}, res => {
//404页面
this.$router.push('/error')
})
}
}
</script>
这样便可以在任何地方使用该组件,使得该组件更易于重用和测试。
props
传参模式可以分为以下几种:
- 布尔模式
- 对象模式
- 函数模式
1.布尔值模式 true
或 false
如上面?例子。
2.对象模式
//路由 index.js
new Router({
routes: [
{
path: '/content',
component: content,
props:{id:1}//此处的id为固定数据
}
]
})
//参数传递方 此处不需要传任何数据
<router-link :to="/content" class="blog-list">阅读全文</router-link>
//参数接受方 重点:props
<script>
export default {
props: ['id'],
data () {
return {
data: '',
url: 'blog/article/'
}
},
mounted () {
this.$http.get(this.url + this.id).then(res => {
this.data = res
}, res => {
//404页面
this.$router.push('/error')
})
}
}
</script>
3.函数模式
//路由 index.js
export default new Router({
routes: [
{
path: '/label',
component: label,
props: (route) => ({
id: route.query.id,
title: route.query.title
})
}
]
})
//参数传递方
<li v-for="item in label_list" :key="item.id">
<router-link :to="{
path: '/label',
query: {
id: item.id,
title: item.title
}
}">{{item.title}}</router-link>
</li>
//参数接受方
<script>
export default {
props: ['id', 'title'],
data () {
return {
data: '',
url: '/Essay/search_by_label/'
}
},
mounted () {
console.log(this.title)//通过参数传递的title
this.$http.get(this.url + this.id).then(res => {
this.data = res
}, res => {
//404页面
this.$router.push('/error')
})
}
}
</script>
网友评论