首页 > 解决方案 > 事件不会通过路由器链接发出

问题描述

我有一个简单的 Vue 应用程序:

const Home = { template: '<div>Home</div>' }
const Bar = {
  methods: {
    bar () {
        alert('bar')
        this.$emit('test')
    }
  },
  template: `
     <div>
        <button  @click="bar()">Bar</button><br/>
        <router-link @click.native="bar()" to="/">Home</router-link>
     </div>
  `
}

const Foo = {
  components: { Bar },
  methods: {
    foo () {
        alert('foo')
    }
  },
  template: '<Bar @test="foo()" />'
}

const router = new VueRouter({
  mode: 'history',
  routes: [
    { path: '/', component: Home },
    { path: '/foo', component: Foo }
  ]
})

new Vue({ router, el: '#app' })

https://jsfiddle.net/tqp5yc6z/5/

通过单击组件中Bar的按钮,Bar将出现两个带有barfoo文本的警报。这是预期的行为。

但是通过单击组件中的Home链接,Bar将只有一个带有bar文本的警报,test不会发出事件,尽管bar会执行方法。我想知道为什么会这样?

标签: vue.jsevents

解决方案


那是因为组件在事件发出Foo之前就已经被销毁了。test这里最好的解决方案是<router-link @click.native="bar()" to="/">Home</router-link><button @click="goHome()">Home</button>where goHomeis 替换:

{
  methods: {
    goHome() {
      alert('bar')
      this.$emit('test')
      this.$router.push('/');
    }
  }
}

推荐阅读