C-Rachel / Share

SOMETHING
1 stars 0 forks source link

Vue 关于ajax #5

Open C-Rachel opened 7 years ago

C-Rachel commented 7 years ago

Vue不像angular js 一样封装了ajax ( $http ),所以需要自己写,也可以配合插件使用

var demo = new Vue({
            el: '#demo',
            data: {
                a: 1,
            },
            methods: {
                ajax: function() {
                    var self = this;
                    var xml = new XMLHttpRequest();
                    xml.onreadystatechange = function() {
                        if(xml.readyState == 4 && xml.status == 200) {
                            var json = JSON.parse(xml.responseText)
                            console.log(self.a)
                            self.a = json.name;
                        }
                    }
                    xml.open("GET", "test.php", true);
                    xml.send();
               }
          }

 })

ajax函数中的this指向的是demo对象的,所以需要var self = this; 保存对demo的指向,然后里面的写法就是原生JS的ajax写法了

php代码简单写

<?php
    echo json_encode(array('skill'=>'read'));
?>

这样就可以在Vue实现ajax请求了

C-Rachel commented 7 years ago

vue-resource

可以使用vue-resource实现ajax

全局使用 Vue.http.get().then()

局部使用 this.$http.get().then()

DEMO

<script type="text/javascript" src="js/vue.js"></script>
<script type="text/javascript" src="js/vue-resource.js" ></script>
<script>
new Vue({
    el: "#demo",
    data: {
        name: "yao",
        arr: ["xu", "chan", "ly"],
    },
    methods:{
        test:function(){
            console.log(111)
            this.$http.get('data/data.json').then(function(data){
                console.log(data.body[0].name);
                console.log(this)
                console.log(this.$el)
            });
        }
    }
})
</script>

vue-resource 也支持 jsonp请求实现跨域

vue-resource 一些补充?     vue-resource

C-Rachel commented 7 years ago

vue+zepto vue+jQuery $.ajax()实现请求