vue.js - 事件不会通过路由器链接发出
问题描述
我有一个简单的 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
将出现两个带有bar
和foo
文本的警报。这是预期的行为。
但是通过单击组件中的Home
链接,Bar
将只有一个带有bar
文本的警报,test
不会发出事件,尽管bar
会执行方法。我想知道为什么会这样?
解决方案
那是因为组件在事件发出Foo
之前就已经被销毁了。test
这里最好的解决方案是<router-link @click.native="bar()" to="/">Home</router-link>
用<button @click="goHome()">Home</button>
where goHome
is 替换:
{
methods: {
goHome() {
alert('bar')
this.$emit('test')
this.$router.push('/');
}
}
}
推荐阅读
- c - Fortran/C 互操作性将结构从 Fortran 传递到 C 与可分配对象
- reactjs - 安装 sass 到 React 项目
- c# - iText7 C#检查PDF在签名后被锁定
- java - 在 ListView 中向右移动 TextView
- javascript - 拼命寻找一个纯JS(ES5)&Vue数据驱动页面生成器的例子
- javascript - 比较两个数组的id | 反应
- python - 如何使子按钮影响父值?
- json - Try-except 在 json 路径中具有三种可能性
- azure - 是否可以在 Azure Pipelines 中编写流程/阶段/步骤脚本?
- android - Android Studio 说我在使用 3.4.1 时需要升级到 Android Gradle 插件 3.2.0