Javascript 如何构造vue.js应用程序,以便在页面加载时从computed属性访问ajax请求数据
下面的代码允许用户在数组中搜索数据。我想用api中的数据替换data属性,但我不知道构造vue.js应用程序的正确方法,因此这些方法可以访问页面加载时调用的ajax数据 我知道我使用axios库调用数据Javascript 如何构造vue.js应用程序,以便在页面加载时从computed属性访问ajax请求数据,javascript,vue.js,vuejs2,axios,Javascript,Vue.js,Vuejs2,Axios,下面的代码允许用户在数组中搜索数据。我想用api中的数据替换data属性,但我不知道构造vue.js应用程序的正确方法,因此这些方法可以访问页面加载时调用的ajax数据 我知道我使用axios库调用数据 Vue.axios.get('https://jsonplaceholder.typicode.com/posts/1').then((response) => { console.log(response.data) }) 我的代码 Vue.js代码 HTML 我想出来了 VUE
Vue.axios.get('https://jsonplaceholder.typicode.com/posts/1').then((response) => {
console.log(response.data)
})
我的代码
Vue.js代码
HTML
我想出来了
VUE
HTML
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;;
}
}
});
<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>
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;;
}
}
});
<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>