动态 Vue 路由器

Dynamic Vue Router

我正在研究 vue 路由器是否是以下场景的最佳方法:

我有一个包含 'n' 个 div 的页面。每个 div 里面都有不同的内容。当用户单击 div 中的按钮时,我希望 div 在单独的浏览器中打开 window(包括其内容)。

如果 link 在单独的 window 中打开,则使用 <router-link> 组件毫无意义,因为应用程序在任何情况下都会从头开始加载。您可以改用锚元素,并为每个 div.

动态生成 href 属性

回答您的问题:

  1. 无法动态创建路由名称,因为所有路由都必须在开始时定义,当应用程序(连同路由器)被初始化时。也就是说,您可以有一个 dynamic route 然后动态生成将与该路由匹配的不同路径。

  2. 如果同一组件实例 运行 在单独的浏览器 window/tab 中,则无法重复使用。

可以创建动态路由器名称。

profileList.vue

<template>
  <main>
    <b-container>
      <b-card
        v-for="username in ['a', 'b']"
        :key="username"
      >
        <b-link :to="{ name: profileType + 'Profile', params: { [profileType + 'name']: username }}">Details</b-link>
    </b-container>
  </main>
</template>

<script>
export default {
  name: 'profileList',

  data () {
    return {
      profileType: ''
    }
  },

  watch: {
    // Call again the method if the route changes.
    '$route': function () {
      this.whatPageLoaded()
    }
  },

  created () {
    this.whatPageLoaded()
  },

  methods: {
    whatPageLoaded () {
      this.profileType = this.$route.path // /user or /place
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style>
</style>

b-containerb-cardb-link取自bootstrap-vue,可以随意更改。

router.js

const router = new Router({
  mode: 'hash',
  base: process.env.BASE_URL,
  linkExactActiveClass: 'active',
  routes: [
    // USERS
    {
      path: '/user/:username',
      name: userProfile,
      component: userProfile
    },
    {
      path: '/user',
      name: 'userList',
      component: profileList
    },

    // PLACES
    {
      path: '/place/:placename',
      name: placeProfile,
      component: placeProfile
    },
    {
      path: '/place',
      name: 'placeList',
      component: ProfileList
    }
  ]
})