vue的好处之一,只关注视图层。对于通信,可以在vue实例对象创建前通过mounted钩子函数发送ajax请求,来拿到json数据。
发送请求通过axios,或者jQuery发送。
请求的数据在response对象里面。并绑定到vue对象data方法里。
1. 要访问的数据
{"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借助第三方包axios发送请求
<!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>