【问题标题】:Vue router issueVue路由器问题
【发布时间】:2018-07-09 11:05:23
【问题描述】:

我在 vue 组件文件中有如下链接。

<li v-for="(word,index) in allWord" v-bind:key="index">
    <router-link :to="{ name: 'word', params: {id: word.id } }">
       {{word}}
    </router-link> 
</li>

我在index.js 文件中的路线设置如下

export default new Router({
    mode: 'history',
    routes: [
        {   
            path: '/',          
            component: MainBody 
        },
        {   path: '/word/:id',
            name: 'word',   
            component: Word 
        }
    ]
});

我得到如下网址

http://localhost:8080/word/4

我正在尝试在word.vue 中捕获 URL 参数,如下所示

<script>
    export default {
        watch: {
            '$route': 'routeChanged'
        },
        methods: {
            routeChanged () {
                console.log(this.$route.params.id);
            }
        }
    }
</script>

问题是当我点击&lt;li&gt;&lt;/li&gt; 时,console 没有任何价值,当我第二次点击时我获得了价值。

为什么会这样?我想第一次获得价值。

【问题讨论】:

    标签: vuejs2 vue-router


    【解决方案1】:

    您的问题是由您正在观察变化引起的。为了更好地理解这个问题,这里有一个时间表:

    1. 用户点击“http://localhost:8080/word/4
    2. Vue 路由器更新$route
    3. 路由器视图更新视图,将MainBody 替换为Word,更新传递的道具并调用createdmounted

    word看来,什么都没有改变,它不调用手表

    从任何方法手动解析$route 不是最干净的解决方案,更好的方法是结合使用props 和watcher 来获取你的id:

    <script>
        export default {
            props: {
                 id: String,
            },
            created() {
                 this.routeChanged();
            },
            watch: {
                'id': 'routeChanged',
            },
            methods: {
                routeChanged () {
                    console.log(this.id);
                },
            },
        };
    </script>
    

    如果使用这个,请确保在您的路由器中指定props: true

        {   path: '/word/:id',
            name: 'word',   
            component: Word,
            props: true,
        },
    

    【讨论】:

    • 感谢@Ferrtbig。您的解决方案工作正常。谢谢。
    • 我在第一次加载 http://localhost:8080/ 时收到 route undefined 消息。为什么要打印?
    • 我的回答不清楚,&lt;script&gt; 部分应该添加到word.vue,而不是mainbody.vue
    • 谢谢@Ferrybig。我将&lt;script&gt; 部分添加到word.vue。谢谢。
    【解决方案2】:

    我建议你在mounted()和updated()中获取值。

    methods: {
      getid: function()
      {
         this.wordid = this.$route.params.id
      } 
    },
    
    watch: {
      wordid: function(val) {
        console.log(this.wordid) // or console.log(val)
      }
    },
    mounted()
    {
       this.getid()
    },
    updated()
    {
     this.getid()
    }
    

    【讨论】:

    • 感谢@Badgy。您的解决方案与我相反。第一次是打印id,但不是从第二次开始。
    • @abuabu 好的,抱歉,因为错误的解决方案浪费了您的时间,我很高兴其他人有正确的想法 :)
    猜你喜欢
    • 2020-09-09
    • 2015-12-23
    • 2019-01-06
    • 2019-12-05
    • 1970-01-01
    • 2021-03-02
    • 2021-02-08
    • 2017-10-02
    • 1970-01-01
    相关资源
    最近更新 更多