【问题标题】:Vue/Vuecli3 - How to route from one component to another with parametersVue/Vue Cli 3 - 如何使用参数从一个组件路由到另一个组件
【发布时间】:2020-03-23 01:48:39
【问题描述】:

我在尝试从一个组件重定向到另一个组件时遇到了问题。它似乎没有路由到我的路由器中指定的 URL 到所需组件,而是停留在我的主页上。我无法弄清楚错误发生在哪里。

我使用的是 Vue CLI 版本 3。
下面是我的 index.js、Home.vue 和 Model.vue

然后是 Home.vue 的图像,然后它显示了当我尝试重定向到我的 href 标记中的链接时会发生什么。
您可以看到它不会转到其他组件,而是停留在我的主页上。

关于这里问题的原因有什么想法吗?谢谢!

/router/index.js

import Vue from 'vue'
import Router from 'vue-router'
import Homefrom '@/components/Home'
import Model from '@/components/Model'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Home',
      component: Home
    },
    {
      path: '/model/:model_tag_name',
      name: 'Model',
      component: Model
      // props: true 
    }
  ]
})  

/components/Home.vue

<template>
  <div class="hello container-fluid">
    <h1>{{msg}}</h1>
    <div class="row">
      <div class="col-4 text-left">
        <ol>
          <li v-for="tag in tags" v-bind:key="tag.model_tag_name">
            <a :href="'/model/'+ tag.model_tag_name"> {{tag.model_tag_name}}</a>
          </li>
        </ol>
      </div>
      <div class="col-8">
        <p>Data</p>
      </div>
    </div>
  </div>

</template>

<script>
var axios = require('axios');

export default {
  name: 'Home',
  data () {
    return {
      msg: 'Welcome to Your Vue.js App',
      tags: []
    }
  },
  mounted: function() {
    var url = 'http://10.0.0.5:5000';
    console.log(url)
    axios.get(url + '/')
      .then((response) => {
        console.log(response.data);
        this.tags = [{"model_tag_name": response.data}];
      })
      .catch(function(error) {
        console.log(error);
      });
  },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

a {
  color: #42b983;
}
</style>

/components/Model.vue

<template>
  <div class="container-fluid">
    <h1> Model </h1>
  </div>

</template>

<script>
var axios = require('axios');

export default {
  name: 'Model',
  data () {
    return {
      model_tag_name: this.$route.params.model_tag_name
    }
  }

}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1, h2 {
  font-weight: normal;
}

a {
  color: #42b983;
}
</style>

http://localhost:8080/

然后,当我单击主页上的 href 链接时,就会发生这种情况。即使 URL 与 Model.vue 的路由器视图匹配,它也会重定向回主页

【问题讨论】:

    标签: javascript vue.js web vue-component vue-router


    【解决方案1】:

    请在 /components/Home.vue 中更新此代码

       <li v-for="tag in tags" v-bind:key="tag.model_tag_name">
    <router-link :to="{ name: 'Model', params: { model_tag_name: tag.model_tag_name}}"> 
     {{tag.model_tag_name}}</router-link>
       </li>
    

    【讨论】:

      猜你喜欢
      • 2019-02-10
      • 1970-01-01
      • 2021-09-14
      • 2019-07-03
      • 2020-07-14
      • 2020-04-04
      • 2021-08-07
      • 2020-07-02
      • 2021-02-16
      相关资源
      最近更新 更多