gpt4 book ai didi

javascript - vue.js 发射 $emit 未被 $on 接收

转载 作者:搜寻专家 更新时间:2023-10-30 22:18:57 27 4
gpt4 key购买 nike

Vue.component('rating-edit', {
template:`
<form>
<input v-model="rating.title" type="text">
<textarea v-model="rating.remark">{{rating.remark}}</textarea>
<button type="button"
@click="submit">
Save
</button>
</form>`,
props:['rating'],
methods: {
submit: function submit () {
let rating = this.rating;
this.$emit('submit', rating);
console.log('submit was emitted');
}
}
});

const aRating = {
title: 'title',
remark: 'remark'
};

let vueApp = new Vue({
el: '#rating-edit-container',
data: {
rating: aRating
}
});

vueApp.$on('submit', function(rating) {
console.log('vue on submit', rating);
});
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="rating-edit-container">
<rating-edit :rating="rating"></rating-edit>
</div>

在遗留前端代码中,我想实现一个基于 vue 的组件化表单,并让它在提交时返回数据。

这是组件代码。请注意触发 this.$emit('submit', rating);

的提交函数
let result = {
props:['rating'],
methods: {
submit: function submit () {
let rating = this.rating;
this.$emit('submit', rating);
console.log('submit fired');
}
}
};

export default result;

现在在遗留代码中,我正在等待事件:

import Vue from 'vue';
import ratingEditVue from './rating-edit.vue';


Vue.component('rating-edit', ratingEditVue);

const aRating = {
title: 'title',
remark: 'remark'
};

let vueApp = new Vue({
el: '#rating-edit-container',
data: {
rating: aRating
}
});

vueApp.$on('submit', function(rating) {
console.log('vue on submit', rating);
});

据我了解 Vue 事件,这应该可行。但是 $on('submit', handlerFunction) 永远不会被调用。

附录:

我已经摆弄了这个例子。我为一开始没有这样做而道歉。

最佳答案

问题是您沿着 rating-edit 组件的相同范围深度发射。

如果您改为使用 this.$parent.$emit 向父级发送,事件将由父级接收。请注意,如果您需要在多个位置或多个深度执行此操作,则需要改用事件总线。

Vue.component('rating-edit', {
template:`
<form>
<input v-model="rating.title" type="text">
<textarea v-model="rating.remark">{{rating.remark}}</textarea>
<button type="button"
@click="submit">
Save
</button>
</form>`,
props:['rating'],
methods: {
submit: function submit () {
let rating = this.rating;
this.$parent.$emit('submit', rating);
console.log('submit was emitted');
}
}
});

const aRating = {
title: 'title',
remark: 'remark'
};

let vueApp = new Vue({
el: '#rating-edit-container',
data: {
rating: aRating
}
});

vueApp.$on('submit', function(rating) {
console.log('vue on submit', rating);
});
<script src="https://vuejs.org/js/vue.min.js"></script>
<div id="rating-edit-container">
<rating-edit :rating="rating"></rating-edit>
</div>

关于javascript - vue.js 发射 $emit 未被 $on 接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45166061/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com