如何在Vue.js中创建自定义链接组件?

问题描述 投票:3回答:1

这看起来像是普通的主/详细用例,但Vue文档中的示例没有这方面的例子。我有一个邮件文件夹页面(路由/:mailbox_id),按日期,主题等显示电子邮件表,我想要一个嵌套路由(/:message_id),当用户点击一行时显示电子邮件的文本。

我能够在Ember(recreating this)中执行此操作,因为Ember创建了一个JavaScript onClick函数来处理路由,并允许您设置HTML元素进行渲染,然后您只需将任何对象传递给子路径。

但我是Vue.js的新手,我一直在浏览文档,但不能理解如何完成同样的事情。我无法弄清楚如何创建一个自定义链接组件,或如何使用内置的Vue <router-link>component(因为我需要它是一个<tr>而不是<a>)才能进入子路径,并传递消息的内容,以便它可以显示。

如果有帮助,这里有一些代码:

路由器

export default new Router({
  routes: [
    {
      path: '/:id',
      name: 'mailbox',
      component: Mailbox,
      props: true,
      children: [
        {
          path: 'mail/:id',
          name: 'mail',
          component: Mail,
          props: true
        }
      ]
    }
  ]
})

组件:Mailbox.vue

<template>
  <div>
    <table>
      <tr>
        <th>Date</th>
        <th>Subject</th>
        <th>From</th>
        <th>To</th>
      </tr>
      <Mail-List-Item v-for="message in messages" :key="message.id" v-bind:message="message"/>
    </table>
    <router-view></router-view>
  </div>
</template>

<script>
  import MailListItem from './Mail-List-Item'

  export default {
    components: { 'Mail-List-Item': MailListItem },
    name: 'Mailbox',
    props: ['messages']
  }
</script>

组件:Mail.vue

<template>
  <div class="mail">
    <dl>
      <dt>From</dt>
      <dd>{{mail.from}}</dd>
      <dt>To</dt>
      <dd>{{mail.to}}</dd>
      <dt>Date</dt>
      <dd>{{messageDate}}</dd>
    </dl>
    <h4>{{mail.subject}}</h4>
    <p>{{mail.body}}</p>
  </div>
</template>

<script>
export default {
  props: ['message', 'messageDate']
}
</script>

组件:Mail-List-Item.vue

<template>
    <V-Row-Link href="mail" mailid="message.id" message="message">
      <td>{{messageDate}}</td>
      <td>{{message.subject}}</td>
      <td>{{message.from}}</td>
      <td>{{message.to}}</td>
    </V-Row-Link>
</template>

<script>
  var moment = require('moment')
  import VRowLink from './V-Row-Link'

  export default {
    name: 'Mail-List-Item',
    props: ['message'],
    components: { VRowLink },
    data: function () {
      return {messageDate: moment(this.message.date).format('MMM Do')}
    }
  }
</script>

组件:V-Row-Link.vue(大部分复制自this repo

<template lang="html">
  <tr
    v-bind:href="href"
    v-on:click="go"
    >
      <slot></slot>
  </tr>
</template>

<script>
import routes from '../Router'

export default {
  props: ['href', 'mailid', 'message'],
  methods: {
    go (event) {
      this.$root.currentRoute = this.href
      window.history.pushState(
        null,
        routes[this.href],
        this.href
      )
    }
  }
}
</script>
vue.js vuejs2 vue-component vue-router
1个回答
7
投票

路由器链接采用tag attribute,您可以使用它将其转换为您喜欢的任何元素。一个例子是......

<router-link tag="tr" :to="'/messages/' + MAIL_ID">{{ MAIL_TITLE }}</router-link>
© www.soinside.com 2019 - 2024. All rights reserved.