【发布时间】:2018-05-18 15:17:57
【问题描述】:
我有一个基本的 Vue2 组件,我正在尝试使用 $emit 将数据从子组件传递到父组件。 注意, my-component 包含一个表格,当我单击一行时,onRowClick 会成功触发,并将“foobar”输出到控制台。出于某种原因,我无法让父方法在 $emit 上触发,并且没有将成功记录到控制台。知道这是为什么吗?
import Vue from 'vue';
import MyComponent from "./components/MyComponent.vue";
window.onload = function () {
var main = new Vue({
el: '#app-v2',
components: { MyComponent },
methods: {
onCouponApplied(data) {
console.log("Success, coupon applied, " + data);
this.saying = "Sunglasses are " + data; //Sunglasses are cool
}
},
data: {
contactEditPage: {
saying: ""
}
}
});
}
MyComponent.vue
export default {
methods: {
onRowClick(event){
this.$emit('applied', 'Cool');
console.log("foobar");
}
HTML
<div id="app-v2">
<my-component @applied="onCouponApplied"></my-component>
{{ saying }} //trying to output: sunglasses are cool
</div>
【问题讨论】:
-
可能
$emit找不到父组件。尝试从您的代码中删除window.onload包装器... -
@AnchovyLegend,这是一个 Plunker (plnkr.co/edit/yldNSHD5S55VykT2FrRn?p=preview),其中包含足够多的代码片段。问题必须在您发布的内容之外,因为该示例似乎有效。
标签: javascript ecmascript-6 vue.js vuejs2 vue-component