vue中的ajax使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        span.active {
            color: red;
        }
    </style>
</head>
<body>
<div id="app">
    <!--<span>ioo</span>-->

   <span v-for="(category,index) in categoryList" @click = 'handlerClick(index,category.id)'>{{category.name}}</span>
    <span v-for = '(each,index) in xian_shi'>{{each}}</span>
    <!--span 中或是其他标签有 for循环,自然到时候,会根据被循环的内容生成几个相对应的标签-->

</div>

<script src="vue.js"></script>
<!--axios-->
<script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.min.js"></script>
<script>
    let vm = new Vue({
        el: '#app',
        data() {
            return {
                categoryList:[],
                currentIndex: 0,
                xian_shi:[],

            }
        },
        methods: {
            handlerClick(i, id) {
                this.currentIndex = i;
                //发起请求
                $.ajax({
                    url: `https://www.luffycity.com/api/v1/courses/?sub_category=${id}`,
                    type: 'get',
                    success:(data)=> {
                        var data = data.data;
                        this.xian_shi=data;
                        console.log(data);
                    }
                })
            }
        },
        created() {
            $.ajax({
                url: "https://www.luffycity.com/api/v1/course_sub/category/list/",
                type: "get",
                success:(data)=> {    //注意此处一定要用箭头函数
                    console.log(data);
                    if (data.error_no === 0) {
                        var data = data.data;
                        let obj = {
                            id: 0,
                            name: '全部',
                            category: 0
                        }
                        this.categoryList = data;
                        // unshift  向数组的第一个位置进行添加
                        //shift是一出数组的第一个位置
                        this.categoryList.unshift(obj)
                        console.log(this.categoryList)
                    }

                },
                error: function (err) {
                    console.log(err)
                }

            })
        }

    })
</script>


</body>
</html>

 

posted @ 2018-12-01 16:46  团子emma  阅读(225)  评论(0)    收藏  举报