Reputation: 4042
I want to update a placeholder (currentUsername) asynchronously with an actual value after loading/rendering the page.
I tried following a sample project (https://github.com/jackfranklin/vue2-demo-proj), but I can't correlate it with my setup. Using vuejs 2.0. I can see the event is triggered, the call is made and something's returned, I've got no errors on my Chrome console, but nothing is updated in the UI. Why is that?
1) html file:
<script src="assets/js/data.js"></script>
2) data.js:
"use strict";
import * as DataXXX from './data.vue';
Vue.component("dataxxx", DataXXX);
var vm = new Vue({
el: "#app",
});
3) data.vue
<template>
<div>
<p v-if="currentUsername == null">
Null username
</p>
<p v-else>
Username: {{ currentUsername }}:
</p>
</div>
</template>
<script>
"use strict";
export default
{
created()
{
awr.EventsBus.$on("requestLoadData", this.loadData);
awr.EventsBus.$emit("requestLoadData", this.loadData);
},
destroyed()
{
awr.EventsBus.$off("requestLoadData", this.loadData);
},
methods:
{
loadData(name)
{
alert("got event");
this.currentUsername = name;
this.fetchGithubData(name);
},
fetchGithubData(name)
{
const url = "http://127.0.0.1/getUsername.php";
alert("requesting url: " + url);
fetch(url).then(response => response.text()).then(data => {
this.currentUsername = data;
console.log("got response: " + data);
});
}
},
data() {
return {
currentUsername: null
}
}
}
</script>
Upvotes: 1
Views: 132
Reputation: 676
The if isn't re-evaluated when you get the response, so the placeholder isn't included in the page.
This line DOES update it, but it's just not shown: this.currentUsername = data;
Change it to something like:
<div>
Username: {{ currentUsername }}
</div
Upvotes: 2