Vue realizes network communication with axios

One of the benefits of vue is to focus only on the view layer. For communication, you can send an ajax request through the mounted hook function before the vue instance object is created to get the json data.
Send the request through axios or jQuery.
The requested data is in the response object. And bound to the data method of the vue object.

1. Data to be accessed

{
    
    
  "name": "bitqian",
  "age": 19,
  "address": {
    
    
    "school": "changsha",
    "home": "hunan"
  },
  "hobby": [
    {
    
    
      "book": "《麦田里的守望者》",
      "game": "《king of glory》"
    },{
    
    
      "language": ["java", "js", "python"],
      "blog": "https://blog.csdn.net/qq_44783283"
    }
  ]
}

2. Vue uses the third-party package axios to send the request

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>axios 请求</title>

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

    <div id="app">
        {
   
   { info.hobby[1].language[0] }}

        <a v-bind:href="info.hobby[1].blog">bitqian's blog</a>

        {
   
   { info.address.home }}
    </div>

    <script>
        let vue = new Vue({
     
     
            el: "#app",
            data() {
     
      // 接收数据并返回
                return {
     
      // 返回的格式要与响应的json格式对应
                    info: {
     
     
                        name: null,
                        address: {
     
     
                            school: null,
                            home: null
                        },
                        hobby: [
                            {
     
     
                                book: null,
                                game: null
                            },
                            {
     
     
                                language: [null, null, null],
                                blog: null
                            }
                        ]
                    }
                }
            },
            mounted() {
     
      // 钩子函数,在虚拟dom执行前,用于发Ajax请求
                // axios.get('../data.json').then(response=> console.log(response.data));
                axios.get('../data.json').then(response=>(this.info=response.data))
            }
        });
    </script>

</body>
</html>

Guess you like

Origin blog.csdn.net/qq_44783283/article/details/108720799