天天看点

vue 路由组件传参

路由组件传参

我们通常把路由直接映射(绑定)的组件称为 路由组件,也只有路由组件才能直接调用路由有关对象:

$router

$route

当我们一个组件即希望作为路由组件使用,又可能作为功能组件(某个页面中的一部分)去使用,这个时候路由组件传参的方式来做到这点

案例

我们对 item.vue 组件进行改造,当我们在 home.vue 的商品列表上移入移出,出现商品信息提示层

<span>      
           <!--下面Item组件找不到item 这里点击传参    这里要写不会主动传递 -->
          <button @click="showTip(item.id,$event)">快速预览</button>
          <button>删除</button>
        </span>
           
// 快速显示的 按钮 接收点击事件的参数,及事件源
    showTip(itemId,{target}){
      // console.log(target)
      let pos  =  target.getBoundingClientRect(); //获取到target的位置信息
      // console.log(pos)
      if(itemId == this.tip.itemId){ //判断itemId是否相等
        this.tip.isShow = false  //这么写须watch监听itemId变化来更新新数据
      }else{
        this.tip={
          // isShow :!this.tip.isShow, 这么写有bug
          isShow:true,
          left:pos.left - pos.width*6, 
          top:pos.top,
          itemId,   // 给data中itemId赋值       
        }
     }
    },
           
created(){ //创建组件是在导航完成之后进行的 

        // console.log(this.$route); //这里接收到home页面传过来商品的id 及其页面信息 可去输出查看
        let itemId = Number(this.itemId || this.$route.params.itemId);//具体信息 先判断this.itemId有值的话说明是功能传参快速预览 否则是视图组件传参     
        // let itemId = Number(this.itemId); //路由中使用了props:true 这里不用传路由的参数了
        if(itemId){ //先判断值有没有
            this.axios({//${itemId} axios传递参数获取数据通过参数获取相对应的数据
                url:`/api/item/${itemId}`
            }).then(res=>{
                //this.loading = false
                this.item = res.data;
                // console.log(this.item)//输出的放请求里面,写外面还没请求到数据呢,肯定输出报错
            }).catch(err=>{});
            
        }
    },
           
vue