路由声明式传参
1、在Home.vue下面的data里面新建一组商品列表,如:
export default { name: "home", data () { return { msg: "我是主页", shop: [ {shop_id:"cap", name: "杯具",price: 30}, {shop_id:"computer", name: "电脑",price: 4999}, {shop_id:"mobile", name: "手机",price: 2988}, {shop_id:"food", name: "食品",price: 49.8}, {shop_id:"clothes", name: "衣服",price: 299}, ] }; } }
2、然后用v-for遍历显示
<ul> <li v-for="(item, index) in shop" :key="item.id"> {{ item.shop_id }} </li> </ul>
3、此时在首页可以看到首页上显示了商品列表
4、在index.js文件中已经配置好的路由规则上,再添加一条规则
const routes = [ {path: '', component: Home}, {path: '/home', component: Home}, {path: '/cart', component: Cart}, {path: '/market', component: Market,children:[ {path: '', component:One}, {path: 'one', component: One}, {path: 'two', component: Two} ]}, {path: '/mine', component: Mine}, {path: '/shop/:shop_id', component:Shop} ]
5、把遍历出来的列表改成,链接形式
<ul> <li v-for="(item, index) in shop" :key="item.id"> <!-- 此处有两种写法 第一种 --> <!-- <router-link :to="'/shop/' + item.shop_id">{{ item.shop_id }}</router-link> --> <!-- 此处有两种写法 第二种 --> <router-link :to="{path: '/shop/' + item.shop_id}">{{ item.shop_id }}</router-link> </li> </ul>
6、在Shop.vue文件里新增一组相同的数据通过计算属性,将路由参数传递过来
export default { name: "shop", data () { return { msg: "我是商品详情页面", shop: [ {shop_id:"cap", name: "杯具",price: 30}, {shop_id:"computer", name: "电脑",price: 4999}, {shop_id:"mobile", name: "手机",price: 2988}, {shop_id:"food", name: "食品",price: 49.8}, {shop_id:"clothes", name: "衣服",price: 299}, ] }; }, component: { shop_params () { console.log(this.$route.params.shop_id); //打印参数 for(var item of this.shop) { if(this.$route.params.shop_id == item.shop_id) { return item; } } } }
7、在Shop.vue 页面上渲染数据
<template> <div id="shop_list"> <h1>{{ msg }}</h1> <h2> {{ shop_params.shop_id }}</h2> <h2> {{ shop_params.name }}</h2> <h2> {{ shop_params.price }}</h2> </div> </template>