如何通过本机事件以编程方式使用 Vue Router?

How to use Vue Router programatically with native events?

我一直在尝试使用 this.$router.push 通过 Vue 路由器使用本机事件,但我不断产生以下错误:

[Vue warn]: Invalid handler for event "click": got undefined

found in

---> <section>

我似乎无法弄清楚为什么,我不得不使用多种解决方案,所有这些都会产生上述错误。其中一些在触发事件之前直接重定向到页面。

我尝试过的事情:

1.

//in JSX
<section nativeOnClick={this.navigationPage('login')}></section>

// in methods I have the following:
methods: {
  navigationPage: function (page) {
    this.$router.push(page)
  }
}

2.

//in JSX
<section nativeOnClick={this.$router.push('login')}></section>

一个有效的解决方案如下:

//in JSX
<section nativeOnClick={this.navigateToLogin}></section>

// in methods I have the following:
methods: {
  navigateToLogin: function () {
    this.$router.push(page)
  }
}

能否请您告诉我我在 1 和 2 中做错了什么。可行的解决方案很好,但这需要我为每个导航创建一个方法。我个人喜欢2!!

感谢任何帮助

NEW 以下是完整的组件定义:

//navbar.js

import styles from './index.styl'
import logo from 'Src/assets/logo.svg'
import menu from 'Src/assets/menu.svg'

export default {
  name: 'NavBar',
  methods: {
    navigationPage: function (page) {
      this.$router.push(page)
    }
  },
  render (h) {
    return (
      <ui-nav class={styles.nav}>
        <ui-section class={styles.navLogo} nativeOnClick={ this.navigationPage('hello') }>
          <ui-image source={logo} />
        </ui-section>
        <ui-spacer />
        <ui-section class={styles.navMenu}>
          <ui-image source={menu} />
        </ui-section>
      </ui-nav>
    )
  }
}

注意:此样式还会自动导航到 /hello(即在单击事件之前)。不知道为什么。

您是否尝试过从 jsx 本机调用中删除 this 保留字?例如:

<section nativeOnClick={ navigationPage('login') }></section>

如果可以的话,post 单个文件组件(或您正在编辑的任何内容)的整个脚本将有助于我了解上下文。

看起来只有一种解决方案有效,但我不明白为什么它有效!

工作解决方案:

<section nativeOnClick={ () => this.$router.push('hello') }></section>

令人困惑的是为什么在没有处理程序的情况下传递参数会产生错误,因为当用一个它没有的函数包装时。 即

<section nativeOnClick={ this.$router.push('hello') }></section> // GIVES error