【问题标题】:Vue-Router doesn't work in a Select OptionVue-Router 在选择选项中不起作用
【发布时间】:2020-10-31 01:18:59
【问题描述】:

我尝试从选择选项创建一个简单的导航,但没有结果。 <router-link><select><option> 内部不起作用

这是我尝试过的:

vue

  <div>
    <select v-model="selected">
      <option v-for="orga in organisations" :key="orga.name">
        <router-link :to="{name: 'Box', params: {orga: orga.route}}">
          {{ orga.name }}
        </router-link>
      </option>
    </select>
  </div>

javascript

  data() {
    return {
      selected: this.$route.params.orga,
      organisations: [
        { name: "Abc", route: "abc" },
        { name: "Lmn", route: "lmn" },
        { name: "Xyz", route: "xyz" }
      ]
    };
  }

【问题讨论】:

  • 你有命名路由“Box”吗?
  • 谢谢,是的,没有选择选项它可以完美运行。我在路径中有名称和 /:orga 的“Box”
  • 您可以在事件上调用另一个函数:@change,以编程方式重定向用户。

标签: vue.js select vue-router router option


【解决方案1】:

如果您想根据select 选项更改视图,则不能在选项标签内使用router-link

但是,您可以通过如下所示的解决方法来实现此目的。在这里,我们将根据select 选项切换视图并更改路线。

Vue.component('compA', {
  template: '<div>{{name}}</div>',
  data() {
    return {
      name: 'Component A'
    }
  }
})

Vue.component('compB', {
  template: '<div>{{name}}</div>',
  data() {
    return {
      name: 'Component B'
    }
  }
})

const routes = [{
    path: '/a',
    component: {
      template: '<compA/>'
    }
  },
  {
    path: '/b',
    component: {
      template: '<compB/>'
    }
  }
];

const router = new VueRouter({
  routes
})

new Vue({
  el: "#app",
  data() {
    return {
      selected: ''
    }
  },
  router,
  methods: {
    routeChange: function(e) {
      this.$router.push(e.target.value)
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
  <div>
    <select @change="routeChange">
      <option></option>
      <option v-for="(c, i) in ['a', 'b']" :key="i">
        {{ c }}
      </option>
    </select>
  </div>
  <router-view/>
</div>

但是这种情况也可以通过动态组件来实现。 docs 对此进行了详细说明,可用于在组件之间切换或动态渲染。

Vue.component('CompA', {
  template: '<div>new component A</div>'
})

Vue.component('CompB', {
  template: '<div>new component B</div>'
})

new Vue({
  el: "#app",
  data() {
    return {
      value: ""
    }
  },
  template: `
  <div>
  <select v-model="value">
    <option v-for="c in ['compA', 'compB']">{{c}}</option>    
  </select>
  <component :is="value" />
  </div>
  `
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.x/dist/vue.js"></script>

<div id="app"></div>

【讨论】:

    猜你喜欢
    • 2020-01-02
    • 2020-05-01
    • 2016-04-21
    • 2013-02-18
    • 2013-08-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-17
    相关资源
    最近更新 更多