day 74 vue 2 axios数据请求 以及组件的学习

前情提要: 

    vue 学习二:

    

    一:  通过axios实现数据请求

      1:json数据语法

        

json数据对象类似于JavaScript中的对象,但是它的键对应的值里面是没有函数方法的,值可以是普通变量,不支持undefined,值还可以是数组或者json对象。

 

// json数据的对象格式:
{
   "name":"tom",
   "age":18
}

// json数据的数组格式:
["tom",18,"programmer"]

 

 

 

复杂的json格式数据可以包含对象和数组的写法。

 

{
 "name":"小明",
 "age":200,
 "fav":["code","eat","swim","read"],
 "son":{
   "name":"小小明",
   "age":100,
   "lve":["code","eat"],
}
}

// 数组结构也可以作为json传输数据。

 

json数据可以保存在.json文件中,一般里面就只有一个json对象。

        2:js 中提供的json 语法转化,

 

       3:ajax  介绍

    

ajax,一般中文称之为:"阿贾克斯",是英文 “Async Javascript And Xml”的简写,译作:异步js和xml数据传输数据。

ajax的作用: ajax可以让js代替浏览器向后端程序发送http请求,与后端通信,在用户不知道的情况下操作数据和信息,从而实现页面局部刷新数据/无刷新更新数据。

所以开发中ajax是很常用的技术,主要用于操作后端提供的数据接口,从而实现网站的前后端分离

ajax技术的原理是实例化js的XMLHttpRequest对象,使用此对象提供的内置方法就可以与后端进行数据通信。

       3.1:ajax的使用

      

ajax的使用必须与服务端程序配合使用,但是目前我们先学习ajax的使用,所以暂时先不涉及到服务端python代码的编写。因此,我们可以使用别人写好的数据接口进行调用。

jQuery将ajax封装成了一个函数$.ajax(),我们可以直接用这个函数来执行ajax请求。

接口地址
天气接口 http://wthrcdn.etouch.cn/weather_mini?city=城市名称
音乐接口搜索 http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=歌曲标题
音乐信息接口 http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.song.play&songid=音乐ID

 

编写代码获取接口提供的数据:

jQ版本

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="js/jquery-1.12.4.js"></script>
   <script>
   $(function(){
       $("#btn").on("click",function(){
           $.ajax({
               // 后端程序的url地址
               url: 'http://wthrcdn.etouch.cn/weather_mini',
               // 也可以使用method,提交数据的方式,默认是'GET',常用的还有'POST'
               type: 'get',
               dataType: 'json',  // 返回的数据格式,常用的有是'json','html',"jsonp"
               data:{ // 设置发送给服务器的数据,如果是get请求,也可以写在url地址的?后面
                   "city":'北京'
              }
          })
          .done(function(resp) {     // 请求成功以后的操作
               console.log(resp);
          })
          .fail(function(error) {    // 请求失败以后的操作
               console.log(error);
          });
      });
  })
   </script>
</head>
<body>
<button id="btn">点击获取数据</button>
</body>
</html>

vue版本:

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <title>Title</title>
   <script src="js/vue.js"></script>
   <script src="js/axios.js"></script>
</head>
<body>
   <div id="app">
       <input type="text" v-model="city">
       <button @click="get_weather">点击获取天气</button>
   </div>
   <script>
       let vm = new Vue({
           el:"#app",
           data:{
               city:"",
          },
           methods:{
               get_weather(){
                   // http://wthrcdn.etouch.cn/weather_mini?city=城市名称
                   axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
                      .then(response=>{
                           console.log(response);

                      }).catch(error=>{
                           console.log(error.response)
                  });
              }
          }
      })
   </script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
 <script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.js"></script>
      <script src="https://cdn.bootcss.com/vue/2.6.10/vue.min.js"></script>

    <title>Title</title>
</head>
<body>
<div id="app">
    <input type="text" v-model="city">
    <button @click="get_wea()">点击查看城市</button>
</div>
</body>


<script>

    let vm =new Vue({
        el:'#app',
        data:{
            city:'广东'

        },
        methods:{
            get_wea(){
                 axios.get("http://wthrcdn.etouch.cn/weather_mini?city="+this.city)
                     .then(response=>{
                          console.log(response);



                     }).catch(error=>{
                         console.log(error.response)



                 })



            }


        }




    })

</script>
</html>
View Code


 

 

 

        4:同源策略

       4:1 什么是同源策略

同源策略,是浏览器为了保护用户信息安全的一种安全机制。所谓的同源就是指代通信的两个地址(例如服务端接口地址与浏览器客户端页面地址)之间比较,是否协议、域名(IP)和端口相同。不同源的客户端脚本[javascript]在没有明确授权的情况下,没有权限读写对方信息。

ajax本质上还是javascript,是运行在浏览器中的脚本语言,所以会被受到浏览器的同源策略所限制。

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="js/vue.js"></script>
    <script src="js/axios.js"></script>
</head>
<body>
    <div id="app">
        <button @click="get_music">点击获取天气</button>
    </div>
    <script>
        let vm = new Vue({
            el:"#app",
            data:{},
            methods:{
                get_music(){
                    axios.get("http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=我的中国心")
                        .then(response=>{
                            console.log(response);

                        }).catch(error=>{
                            console.log(error.response)
                    });
                }
            }
        })
    </script>
</body>
</html>
View Code

        4:2当不是同源时会被浏览器拦截,报如下错.

    

Access to XMLHttpRequest at 'http://tingapi.ting.baidu.com/v1/restserver/ting?method=baidu.ting.search.catalogSug&query=%E6%88%91%E7%9A%84%E4%B8%AD%E5%9B%BD%E5%BF%83' from origin 'http://localhost:63342' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

      报错:  

  

 

           4:3   ajax跨域之方案cors

          

          4:4示意图

      4:5: 同源策略总结

 

    二:       组件化开发

1:组件的概念

 

  2:全局组件

<div id="app">
    <addnum></addnum>
    <addnum></addnum>
    <addnum></addnum>
    <addnum></addnum>
    <addnum></addnum>
</div>

<script>
    Vue.component("addnum",{
        template:'<div><input type="text" v-model="num"><button @click="num+=1">点击</button></div>',
        data: function(){
            // 写在这里的数据只有当前组件可以使用
            return {
                num:1,
            }
        }
    });


    var vm = new Vue({
        el:"#app",
        // 这里写的数据是全局公用的,整个文件共享
        data:{

        }
    })
</script>

 

原文地址:https://www.cnblogs.com/baili-luoyun/p/10762860.html