我的(vuejs)主页包含以下内容:
模板: <h3>{{ strings.home_headline }}</h3>
脚本:
data() {
return {
strings: []
};
},
methods: {
fetchData: function(){
var self = this;
// get translatable strings
axios
.get(MY_API_URL, {
headers: { "X-Locale": self.locale }
})
.then(function(data) {
self.strings = data.data;
// This console works and outputs the right content;
console.log("strings: ", self.strings);
// outputs the text that should come in the H3
console.log(strings.home_headline)
})
.catch(function(error) {
console.log("Error", error);
});
}
},
created() {
this.fetchData();
}
该console.log
作品有效,但模板h3
为空,直到滚动第一个像素,然后所有内容均用文本填充。我在这里做错了什么?
将成员从数组切换到对象
return {
// you need the fields here as well - an "empty" prepared object
strings: {
home_headline: "", // more fields go here
}
};
并更改您正在使用的救生钩,应该可以解决您的问题:
async mounted() {
await this.fetchData();
}
var app = new Vue({
el: '#app',
data() {
return {
strings: { home_headline: ""}
};
},
methods: {
fetchData: function() {
self = this;
//will lead to error
axios
.get("error", {
headers: {
"X-Locale": self.locale
}
})
.then(function(data) {
self.strings.home_headline = "TATü";
})
.catch(function(error) {
self.strings.home_headline = "TATö";
});
}
},
async mounted() {
await this.fetchData();
},
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<h3>{{ strings.home_headline }}</h3>
</div>
为了使vue启用更改更新,您需要已经在对象上指定了字段。
关于生命周期挂钩:
created,模板和Virtual DOM尚未安装或呈现。(https://www.digitalocean.com/community/tutorials/vuejs-component-lifecycle#creation-(初始化))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句