【问题标题】:how to programmatically return to Vue cli's pre-made Home.vue如何以编程方式返回 Vue cli 的预制 Home.vue
【发布时间】:2019-05-05 13:42:55
【问题描述】:

我正在使用 Vue CLI 3,它创建了一些路由。一个是 Home.vue。在我的程序中,我试图以编程方式转到不同的页面。我在 router.js 中添加了我需要的路由,但保留了已经为 Home.vue 和 About.vue 创建的路由。它工作正常,直到我到达“家”并收到警告:[vue-router] 名为“家”的路由不存在。'

代码如下:

 <template>
    <div class='secondItem'>
         <h4 v-for="item in menuItems" 
    @click="bindMe(item)" v-bind:class="{'active':(item === current)}">{{item}}</h4>
    </div>
    </template>
    <script>
    export default {
            name: 'Header',
            data() {
                return {
                    current: '',
                    menuItems: ['Home', 'About', 'Portfolio', 'Contact'],
                }
            },
            methods: {
                bindMe(item) {
                    this.current = item;
                    this.$router.push({
                            path: item
                        })
                }

            }
        }
    <script>

【问题讨论】:

    标签: vue.js vue-router


    【解决方案1】:

    你在使用named routes吗?在这种情况下,您需要使用name 而不是path

    this.$router.push({
      name: item
    })
    

    此外,您的示例可以简化很多。试试这个:

    <template>
      <div class="secondItem">
        <router-link :to="{ name: item }" tag="h4" active-class="active" v-for="item in menuItems" v-bind:key="item">{{item}}</router-link>
      </div>
    </template>
    
    <script>
      export default {
        name: 'Header',
        data() {
          return {
            menuItems: ['Home', 'About', 'Portfolio', 'Contact']
          }
        }
      }
    <script>
    

    【讨论】:

    • 我试过了,但没有用,然后我在你回答后又试了一次,这次我检查了值并将其全部更改为小写的“home”,它起作用了。傻我:>)
    • 是的,名称区分大小写。你可以在你的:to-attribute 中使用item.toLowerCase()
    猜你喜欢
    • 1970-01-01
    • 2020-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-19
    • 1970-01-01
    • 2015-08-06
    • 1970-01-01
    相关资源
    最近更新 更多