
Vue 3 默认要求显式声明子组件触发的自定义事件(emits),否则事件将被静默忽略;若未在子组件中声明 emits: ['newPicture'],即使调用 this.$emit('newPicture', ...),父组件也无法监听到该事件。
vue 3 默认要求显式声明子组件触发的自定义事件(`emits`),否则事件将被静默忽略;若未在子组件中声明 `emits: ['newpicture']`,即使调用 `this.$emit('newpicture', ...)`,父组件也无法监听到该事件。
在 Vue 3 的 Options API 项目中(如你当前使用的写法),子组件必须显式声明它将通过 $emit 触发的事件名,否则这些事件会被框架过滤掉,父组件无法监听——这正是你遇到 console.log("emit ontvangen") 完全不执行的根本原因。
你的 ImageUpload 组件中已正确调用:
this.$emit('newPicture', imageData);
但缺少关键的 emits 声明,导致该事件被 Vue 忽略。
✅ 修复方法:在 ImageUpload.vue 的组件选项中添加 emits 数组
Vue 3 组合式 API 与 <script setup> 最佳实践,涵盖代码组织、useXxx 模式、组合式函数设计、Store 集成、响应式优化及功能抽取。</p> </div> <a rel="nofollow" href="/xiazai/skill8748" title="vue-composition-api-best-practices" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div> <pre class="brush:php;toolbar:false;">export default { props: ['imgUrl'], emits: ['newPicture'], // ← 关键!声明允许向外抛出的事件 mounted() { this.setUpCroppie(); }, data() { return { croppie: null, croppieImage: '', selectedFile: '', picture: '', url: '', }; }, methods: { // ... 其余方法保持不变 setImage() { this.croppie.result({ type: 'canvas', size: 'viewport' }) .then(blob => fetch(blob)) .then(res => res.arrayBuffer()) .then(buf => new File([buf], this.croppieImage.name, { type: 'image/png' })) .then(file => { this.croppieImage = file; this.picture = URL.createObjectURL(this.croppieImage); const imageData = { picture: this.picture, file: this.croppieImage }; console.log("klaar voor emit...?"); this.$emit('newPicture', imageData); // ✅ 现在能被父组件捕获 this.url = ''; }); }, // ... } };</pre> <p>⚠️ 注意事项:</p> <ul> <li>emits 是 Vue 3 的<strong>强制性最佳实践</strong>(尤其在使用 <script setup> 或 TypeScript 时更为关键),不仅影响事件传递,还参与模板编译时的事件校验与 IDE 类型推导;</script>
热门下载
相关下载
精品课程
