动态Vue路由器

时间:2018-12-26 14:23:49

标签: vue.js vue-router

我正在研究在以下情况下vue路由器是否是最佳方法:

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

  • 可以动态创建要路由到的路由名称/组件吗?由于我有n个可动态创建的div,因此我无法为每个名称/组件硬编码

       连结文字  

  • 我想避免使用同一组件实例(通过带参数的路由),因为我可能希望同时打开多个div(每个div在自己的浏览器窗口中)

2 个答案:

答案 0 :(得分:2)

如果链接是在单独的窗口中打开,则使用<router-link>组件是没有意义的,因为在任何情况下应用程序都会从​​头开始加载。您可以改用锚元素,并为每个div动态生成href属性。

要回答您的问题:

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

  2. 如果同一组件实例在单独的浏览器窗口/选项卡中运行,则无法重用该组件实例。

答案 1 :(得分:0)

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

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
    }
  ]
})
相关问题