将 GET 结果保存在文本文件中最终会陷入无限循环



我一直在尝试将从GET请求中获得的字符串保存到文本文件中。出于某种原因,它最终进入了一个无限循环,如果我不使用created(),它根本不起作用,story只是保持空。

<div id="app">
<p>{{story}}</p>
<a id="link" v-bind:href="url" target="_blank" download="file.txt">Download</a>
</div>
<script>
var str = {
data: function () {
return {
story: '',
file: null,
}
},
methods: {
async getStory(id) {
var req = 'http://localhost:8080/api/story/' + id
try {
const response = await axios.get(req);
return response.data.story;
} catch (error) {
console.error(error)
}
return false;
},
async getLetter() {
var story = await this.getStory(this.$route.params.id);
this.story = letter;
},
textFile() {
var data = [];
console.log(this.story);
data.push(this.story);
var properties = {
type: 'text/plain'
};
try {
this.file = new File(data, "file.txt", properties);
} catch (e) {
this.file = new Blob(data, properties);
}
this.url = URL.createObjectURL(this.file);
}
},
created() {
this.getLetter();
},
updated() {
this.textFile();
}
}
</script>

使用 HTML5 功能保存文件是否明智?

Axios 是一个基于 promise 的 HTTP API,因此删除 async/await 就可以了

getStory(id) {
return new Promise((res, rej) => {
var req = 'http://localhost:8080/api/story/' + id
axios.get(req).then((response) => {
res(response.data.story);
}).catch((err) => {
rej(err);
});
})
},
getLetter() {
var story = this.getStory(this.$route.params.id);
this.story = letter;
}

还有一件事,有循环,所以没有无限循环发生。相反,请求未完成。

我想你可以试试下面的代码,看看

var app = new Vue({
el: '#app',
data () {
return {
story:"",
url:"",

}
},
created(){
	this.getLetter();
},
methods: {
getStory:function(id) {
var req = 'http://localhost/website-one-pages/slipt.php?id=' + id;
				 axios.get(req).then((response) => {
		              this.story = response.data;
		              
		              //set download
		              var data = [];
		              data.push(this.story);
		              var properties = {
			            type: 'text/plain'
			          };
			          try {
			            this.file = new File(data, "file.txt", properties);
			          } catch (e) {
			            this.file = new Blob(data, properties);
			          }
			          this.url = URL.createObjectURL(this.file);
			          //end set download
		           }).catch((error)=>{
console.log(error);
});
},
getLetter() {
var id =2;//example id=2 
this.getStory(id);
},
}

})
<div id="app">
<p>{{story}}</p>

<a id="link" v-bind:href="url" target="_blank" download="file.txt">Download</a>

最新更新