[英]How to structure vue.js app so I can access ajax request data from computed property on page load
我有以下代碼(如下),它使用戶可以搜索數組中的數據。 我想用來自api的數據替換data屬性,但我不知道構建vue.js應用程序的正確方法,因此這些方法可以訪問頁面加載時調用的ajax數據。
我知道我使用axios庫來調用數據。
Vue.axios.get('https://jsonplaceholder.typicode.com/posts/1').then((response) => {
console.log(response.data)
})
我的密碼
https://jsfiddle.net/bny191f7/1/
Vue.js代碼
new Vue({
el: '#app',
data: {
searchString: "",
users: [{ //____________I want to replace this data with api data
"name": "Bob"
},
{
"name": "Angel"
},
{
"name": "Whatever"
}
]
},
computed: {
filterUsers: function() { //___________And insure this has access to it
//___________so the app continues to work
var users_array = this.users,
searchString = this.searchString;
if (!searchString) {
return users_array;
}
searchString = searchString.trim().toLowerCase();
users_array = users_array.filter(function(item) {
if (item.name.toLowerCase().indexOf(searchString) !== -1) {
return item;
}
})
return users_array;;
}
}
});
HTML
<form id="app" v-cloak>
<input type="text" v-model="searchString" placeholder="Enter your search terms" />
<ul>
<li v-for="user in filterUsers">
<p>{{user.name}}</p>
</li>
</ul>
我想到了。
VUE
new Vue({
el: '#app',
data: {
searchString: "",
users: undefined
},
mounted: function () {
Vue.axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response);
this.users = response.data;
console.log(this.users);
})
.catch(function (error) {
console.log(error);
});
},
computed: {
filterUsers: function () {
var users_array = this.users,
searchString = this.searchString;
if(!searchString){
return users_array;
}
searchString = searchString.trim().toLowerCase();
users_array = users_array.filter(function(item){
if(item.title.toLowerCase().indexOf(searchString) !== -1){
return item;
}
})
return users_array;;
}
}
});
HTML
<form id="app" v-cloak>
<input type="text" v-model="searchString" placeholder="Enter your search terms" />
<ul>
<li v-for="user in filterUsers">
<p>{{user.title}}</p>
</li>
</ul>
</form>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.