我正在编写一个 Vue 应用程序,但我不知道将文件从一个 View 发送到另一个 View 的最佳方式是什么。 我有一个 View FileUploadView 允许您选择本地文件:
function selectFile() {
this.file = this.$refs.file.files[0];
}
function sendFile() {
const fileReader = new FileReader();
try {
fileReader.readAsText(this.file);
fileReader.onloadend = function() {
console.log(fileReader.result); // This are the contents of a file
this.$router.push({
name: '/textInput',
params: {
inputText: fileReader.result
}
});
}
} catch (err) {
console.log(err)
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<input type="file" ref="file" id="fileUpload" class="form-control-file .form-control-lg" @change="selectFile" />
<button type="submit" class="btn btn-primary" /> Submit
</button>
当此 View 加载文件时,我想将用户重定向到 TextInputView View 并传递 file.txt 的全部内容 TextInputView 是一个如下所示的 View :
function onTextChange() {
var inputText = document.getElementById("inputTextField").value;
mock_send_data_to_server_and_return_results(inputText);
}
function mock_send_data_to_server_and_return_results(someText) {
document.getElementById("outputTextAfterPostOnServer").innerText = someText.toUpperCase();
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="container">
<div class="row">
<div class="col">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">InputText</span>
</div>
<textarea id="inputTextField" class="form-control" aria-label="With textarea" onChange="onTextChange()"></textarea>
</div>
</div>
<div class="col">
<div class="jumbotron jumbotron-fluid">
<div class="container">
<h1 class="display-4">Output text</h1>
<p class="lead" id="outputTextAfterPostOnServer">Here the input text will be modified by backend, and returned.</p>
</div>
</div>
</div>
</div>
</div>
textarea
元素如果被传递则应该包含文件的原始文本,否则为空。然后,此文本将与 POST 请求一起发送到 DJANGO 服务器,进行分析(更正)并在同一 View 中返回到 #outputTextAfterPostOnServer
组件。
这个问题不是关于将文本从 TEXTAREA
发送到 #output...
。
我想知道将文本从 FileUploadView 发送到 TextInputView 的正确方法是什么。现在我知道,我可以将它作为 Prop 传递给 VueRouter,但这将我的文本限制为 2048 个字符。如何将整个文本传递给 TextInputView? 我应该:
- 使用 vuex,
- 在 FileUploadView 中创建 TextInputView 组件并显示它 仅 v-if 文件已被选中?
- 我应该在后端发送文件吗? 从后端检索某种 token ,更改传递 token 的 View 作为参数并使用 token 检索文本?
- 一些其他方法。
我正在做的项目是 here .
最佳答案
此链接可能对您有所帮助。 https://dev.to/alexmourer/sharing-data-between-components-invuejs-48me
如果您以这种方式共享数据时遇到任何问题,我喜欢 Vuex 选项。它们有不同类型的存储,默认为本地存储,存储大约 25MB。
关于javascript - 在 Vue View 之间发送文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57913949/