vue + axios post请求数据

vue更新到2.0之后,作者就宣告不再对vue-resource更新,而是推荐的axios。所以本篇文章介绍下通过axios获取数据,然后用vue进行渲染页面

准备工作引入vue和axios库

     <!-- vue -->
    <script src="https://unpkg.com/vue/dist/vue.js"></script>
    
    <!-- axios -->
    <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

定义页面模板,显示用户信息的表格

<div id="app">
            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>名称</th>
                        <th>昵称</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="user in users">
                        <td>{{ user.id  }}</td>
                        <td>{{ user.username  }}</td>
                        <td>{{ user.age  }}</td>
                    </tr>
                </tbody>
            </table>
        </div>

vue

<script>
        // 数据Model
        var userData = {
            user: [{
                    id: '1',
                    username: 'uc小天',
                    age: 20
                }, {
                    id: '1',
                    username: '斗鱼',
                    age:  28
                }, {
                    id: '1',
                    username: 'Dio',
                    age:  30
                }]
        }
        
        // vue 会将数据填充到页面模板
        var vm = new Vue({
            el: '#app',
            data: userData
        })
    </script>

通过axios发起post请求获取用户数据

<script>
    var config = {
      baseURL: 'http://api.xiehur.com/'
    };
    
    var fileData = new FormData();
    fileData.append("token", "ZHSy75asLZa4nwwBc8lJYBOy0U-oSTxD_1484494816");
    fileData.append("app_id", "xxxxxx-xxx-xxxxxxx");
    fileData.append("page", "1");
    fileData.append("page_size", "10");
 
    axios.post('wechat/grouplist', fileData,config)
        .then(function (response) {
            if (response.data.code == 0) {
                userData.people =response.data.items;
            }
        })
        .catch(function (error) {
            console.log(error);
        });
</script>

查看完成的结果

DAB27A79-DA7F-42B5-A102-0EA7B14B2635.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 梁文道、刘擎、许纪霖、朱大可 口述 / Vincent 整理 他13岁就学习雄辩术,才华横溢、放荡不羁,但同你我一...
    VincentChan文森阅读 575评论 2 5
  • 苓子和司机小赵及另外一个年轻后生小齐一起出差。 路上一直在下雨,雨刮器的声音甚至盖过了车内电台的音乐声。 算起来,...
    木徒阅读 305评论 0 1
  • 立志,勤学,改过,责善
    苦做舟11阅读 118评论 0 0
  • 1、完成800字的写作 2、检讨这半个月来的生活 3、突然反省不该让女儿看动画片 4、知道万恶懒为首,带孩子不可懒...
    小确幸HYF阅读 172评论 0 0