javascript - 从 vue.js 中的子发射传递时值未定义
问题描述
我不确定为什么会发生这种情况,因为我的两个方法(父和子都被调用)但实际数据没有被传递,即使我尝试传递一个简单的字符串,当从我的父母从发射接收数据:(
有人可以帮助我或者提供解释吗?
我的应用程序在 dom 中像这样呈现(这都是 html 注入的一部分,而不是 vue-cli)
<div id="app">
<div>
<b-button v-b-modal.modal-1>upload files</b-button>
<b-modal id="modal-1" title="BootstrapVue" ok-title="upload">
<div>
<file-uploader v-on:child-to-parent="logChildData()"></file-uploader>
</div>
</b-modal>
</div>
</div>
这是我的子组件
//component constructor
var fileUploader = Vue.extend({
template: ' <div><div id="container" class="flexContainer"><div v-for="img in images" :key="img.name"><div :id=img.name><img height="80px" width="80px" :src=img.src alt="uploaded image"><button @click="removeItem(img.name)">X</button></div></div></div><input type="file" multiple @input="handleUpload($event)"></div>',
data() {
return {
images:[],
pdfs:[],
}
},
methods: {
//send files back up to parent component where they can be manipulated
sendDatatoParent(){
console.log('sending data to parent')
this.$emit('child-to-parent', 'a string to send')
},
async handleUpload(e) {
//check file type and sort into pdfs or images based on their file extension
var files = e.target.files
for(i = 0; i< files.length; i++){
if(files[i].type === 'application/pdf'){
this.pdfs.push(files[i])
}else{
if(files[i].type === 'image/jpeg' || files[i].type === 'image/png' || files[i].type === 'image/gif' || files[i].type === 'image/jpg'){
//create the thumbnail img and add it to the image object
//console.log(files[i].name)
this.buildUrl(files[i])
}
}
}
//console.log('pdfs',this.pdfs)
//console.log('images',this.images)
this.sendDatatoParent()
},
},
})
// register the file uploader component inside your app so your app has a name to reference the component by
Vue.component('file-uploader', fileUploader)
这是我的父母,我应该能够从 $emit 记录数据
// create the main vue app (this contains and renders all your components, it is the parent)
new Vue({
el: '#app',
methods:{
/*
listens for the custom $emit event (childToParent) which is passed to your child component (see above ^)
when fired it will grab the child's data and pass the value here (the parent component)
*/
logChildData(value){
console.log('logging the value from emit',value)
}
}
})
解决方案
在父组件的子组件标记中,您正在调用不带参数的父函数,因此该值将不存在。完全通过$event
或删除括号(推荐)。这样做:
v-on:child-to-parent="logChildData"
或者:
v-on:child-to-parent="logChildData($event)"
推荐阅读
- python - 列表中元素的最大总和
- google-apps-script - 状态 2020 年 12 月 - “部署 ID 未与当前项目关联”
- memory-management - 使用 Fortran 90 将 txt 文件读入可分配数组时出现错误结果
- python - 尝试创建虚拟环境时 pipenv FileNotFoundError
- r - 如何确定哪些患者出现在 R 中的两个 ID 下?
- python - Django ManyToMany 字段不接受正确的模型
- php - SSL 例程:tls_process_server_certificate:证书验证失败
- javascript - 在 JavaScript 中检查数组不包含任何数字
- android - 运动布局材料设计扩展按钮错误
- python - 如何更改 Django 表单中下拉列表的标签?