我正在将Laravel 5.7与vue.js和mysql一起使用
当我点击父组件中的“提交”按钮时,是否还可以通过子组件(图像)提交所选文件?
父组件-该组件有一个文本框,一个按钮用于保存并声明一个组件以呈现用于选择图像的html。
<template>
<div>
<label class="control-label">Name</label>
<input name="Name" type="text" v-model="saveForm.Name">
<images></images> //Child Component declaration
<button type="button" @click="store()">
Save
</button>
</div>
</template>
<script>
export default {
data() {
return {
saveForm: {
Name: ''
}
};
},
methods: {
store() {
axios.post("my route", this.saveForm).then(response => {
if(response.data.Status) {}
});
}
}
}
</script>
图像组件(子组件),实际上,该组件有58张左右的图像。
<template>
<div>
<input type="file" id="Image">
</div>
</template>
<script>
export default {
data() {
},
methods: {
}
}
</script>
答案 0 :(得分:0)
您可以使用$refs
从父组件访问文件:
还有一个FormData对象,可通过ajax上传文件:
https://blog.teamtreehouse.com/uploading-files-ajax
父组件:
<template>
...
<!-- Declare a 'ref' attribute on the child component -->
<images ref="imageComponent"></images>
...
</template>
<script>
export default {
data() {
return {
saveForm: {
Name: ''
}
};
},
methods: {
store() {
// get the child attribute's files through the $refs properties
let files = this.$refs.imageComponent.$refs.fileInput.files;
// Create a new FormData object.
let formData = new FormData();
// Loop through each of the selected files.
for (let i = 0; i < files.length; i++) {
let file = files[i];
// Check the file type.
if (!file.type.match('image.*')) {
continue;
}
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// Add the Name
formData.append('Name', this.saveForm.Name);
// Ajax request
axios.post("my route", formData).then(response => {
if(response.data.Status) {}
});
}
}
}
</script>
子组件:
<template>
...
<!-- Declare a 'ref' attribute on the file input -->
<input ref="fileInput" type="file" id="Image">
...
</template>
<script>
export default {
data() {
},
methods: {
}
}
</script>