记一次vue2路由参数传递this指针问题

需要船体一个data()内的对象到另一个页面。

<player-card v-for="(note, key) in sortedtNodes"
                 :imgurl="note.avarUrl"
                 :playerId="note.playerId"
                 :title="note.playerName"
                 :label="note.kIndex"
                 @click.native="$router.push({name: 'player_topics', params: { playerId: note.playerId, playerName: note.playerName, dateFroHome: this.date }})"></player-card>

在跳转到的页面却并没有获取到,手动打印一下是这样的结果:

尝试将参数设置为固定值:dateFroHome: '2017-04-28'这样后端是可以获取到的。所以这里确定是this指针问题。

所以这里的dateFroHome: this.date 的this是player-card组件里的this吧。

问题找出来了,怎么解决呢?

看了下官方文档《组件数据流》中的内容:

简单来说vue是不允许将父组件中的对象引用直接传递给子组件的,为了应对这种情况,vue提供了两种方法:

1.定义一个局部变量,并用 prop 的值初始化它:

props: ['initialCounter'],
data: function () {
  return { counter: this.initialCounter }
}

 

2.定义一个计算属性,处理 prop 的值并返回。

props: ['size'],
computed: {
  normalizedSize: function () {
    return this.size.trim().toLowerCase()
  }
}

可以看这样就能保证父组件的属性this.xxx都保留在父组件中给你了。

所以我修改了一下项目:

在父组件的computed中定义一个啥啥啥:

computed: {
      thisDate: function () {
        var this_date = this.date;
        return this_date;
      }
    }

然后直接传递这个thisDate就可以了:

@click.native="$router.push({name: 'player_topics', params: { playerId: note.playerId, playerName: note.playerName, dateFroHome: thisDate }})"

 

posted @ 2017-05-02 20:38  每日健身  阅读(1402)  评论(0编辑  收藏  举报