如何构建vue.js应用程序,以便我可以在页面加载时从compute属性访问ajax请求数据

时间:2017-09-02 05:17:37

标签: 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)
})

我的代码

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>

1 个答案:

答案 0 :(得分:1)

我明白了。

<强> 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>