简体   繁体   English

vue js 组件中的 this.$route 只返回 undefined

[英]this.$route in vue js component just returns undefined

I'm trying to get the params from the url into a method into in a vue component.我正在尝试将参数从 url 获取到 vue 组件中的方法中。

I've read that I'm meant to use this.$route but no matter what i do it returns undefined, I've seen a few different similar issues but their fixes haven't worked for me.我读过我打算使用 this.$route 但无论我做什么它都会返回未定义,我已经看到了一些不同的类似问题,但他们的修复对我不起作用。

<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>

I've used this.$route in the template and it works correctly and show it.我在模板中使用了 this.$route ,它可以正常工作并显示它。

I'm not sure what I need to do to make it show the params.我不确定我需要做什么才能让它显示参数。

I'm new to vue so might be doing the whole process wrong but basically the app will read the links and only show folder content, so if it the url is /cards?folder=medium it will only show data with the folder data.我是 vue 的新手,所以可能整个过程都做错了,但基本上应用程序会读取链接并且只显示文件夹内容,所以如果它的 url 是 /cards?folder=medium 它只会显示文件夹数据的数据。 So if you know a better way just let me know!因此,如果您知道更好的方法,请告诉我!

Otherwise can you see why its not showing the route?否则你能明白为什么它不显示路线吗?

Here's my router vue file if it helps:如果有帮助,这是我的路由器 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',
});

In order to access this you should NOT use arrow functions.为了访问this ,您不应该使用箭头功能。 Use regular functions instead:改用常规函数:

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

This is noted in Vue docs, for example here https://v2.vuejs.org/v2/api/#data bottom note.这在 Vue 文档中有所说明,例如这里https://v2.vuejs.org/v2/api/#data底部注释。

you can use the object definition method shorthand (achieving the same result as in Egor Stambakio's answer , but with less characters, yay!).您可以使用对象定义方法速记(实现与Egor Stambakio 的答案相同的结果,但字符更少,耶!)。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM