vue js 组件中的 this.$route returns undefined

this.$route in vue js component just returns undefined

我正在尝试将参数从 url 获取到 vue 组件中的方法中。

我读到我打算使用 this.$route 但无论我做什么 returns 未定义,我已经看到了一些不同的类似问题,但他们的修复没有奏效对我来说。

<template>
  {{ this.$route.query }}
</template>
<script>
  export default {
    name: 'cards',
    data: () => ({
      items: [
        {
          id: 1,
          title: '8 myths about mobile interfaces',
          link: 'https://medium.muz.li/8-myths-about-mobile-interfaces-390d9e2cee33',
          folder: 'medium',
          order: 1,
        },
        {
          id: 2,
          title: 'Asking your user’s gender, the new skeuomorphism, upside-down UIs and more',
          link: 'https://uxdesign.cc/asking-your-users-gender-the-new-skeuomorphism-upside-down-uis-and-more-e108ef888030',
          folder: 'medium',
          order: 2,
        },
      ],
    }),
    methods: {
      link: () => {
        console.log(this.$routes.query);
      },
    },
  };
</script>

我在模板中使用了 this.$route 并且它可以正常工作并显示它。

我不确定我需要做什么才能让它显示参数。

我是 vue 的新手,所以可能整个过程都做错了,但基本上应用程序会读取链接并且只显示文件夹内容,所以如果 url 是 /cards?folder=medium只会显示包含文件夹数据的数据。所以,如果您知道更好的方法,请告诉我!

不然你能看出为什么不显示路线吗?

如果有帮助,这是我的路由器 vue 文件:

import Vue from 'vue';
import VueRouter from 'vue-router';

import cards from './cards/cards';

Vue.use(VueRouter);

export default new VueRouter({
  routes: [
    {
      path: '/cards',
      name: 'cards',
      component: cards,
    },
  ],
  mode: 'history',
});

为了访问 this,您不应使用箭头函数。改为使用常规函数:

methods: {
  links: function() {
    console.log(this.$route) // should work
  }
}

这在 Vue 文档中有注明,例如此处 https://vuejs.org/v2/api/#data 底注。

您可以使用 object definition method shorthand (achieving the same result as in ,但字符较少,耶!)。

methods: {
  links() {
    console.log(this.$route) // should also work
  }
}