一、本地读取数据

1-1 读取数据

  1. // data/carts.json
  2. [
  3. {
  4. "isSelected": true,
  5. "productCover": "https://img3.doubanio.com/view/subject/m/public/s33510542.jpg",
  6. "productName": "纸上行舟",
  7. "productInfo": "青年作者黎幺短篇小说首度结集",
  8. "productPrice": 57,
  9. "productCount": 3,
  10. "id": "0001"
  11. },
  12. {
  13. "isSelected": true,
  14. "productCover": "https://img3.doubanio.com/view/subject/m/public/s33497735.jpg",
  15. "productName": "我可能得抑郁症了!舟",
  16. "productInfo": "青年作者黎幺短篇小说首度结集",
  17. "productPrice": 54,
  18. "productCount": 2,
  19. "id": "0002"
  20. },
  21. {
  22. "isSelected": true,
  23. "productCover": "https://img3.doubanio.com/view/subject/m/public/s33474961.jpg",
  24. "productName": "绕日飞行",
  25. "productInfo": "驯马、飞行、成长、爱情",
  26. "productPrice": 22,
  27. "productCount": 3,
  28. "id": "0003"
  29. }
  30. ]
  1. //index.html
  2. <body>
  3. <div id="app">
  4. </div>
  5. <script>
  6. var vm = new Vue({
  7. el: "#app",
  8. data:{
  9. products:[]
  10. },
  11. mounted(){
  12. axios.get('./data/carts.json').then(res=>{
  13. this.products = res.data
  14. })
  15. }
  16. })
  17. </script>
  18. </body>

1-2 发送http请求

先跨域:npm i axios-jsonp-pro -S

  1. import axios from 'axios-jsonp-pro';
  2. //使用
  3. mounted(){
  4. var url = "https://douban.uieee.com/v2/movie/in_theaters";
  5. axios.jsonp(url).then(res=>{
  6. this.movies = res.subjects;
  7. })
  8. }
  9. //数据渲染
  10. <template>
  11. <div id="app">
  12. <div class="item" v-for="item of movies" :key="item.id">
  13. <p>{{item.title}}</p>
  14. <!-- vue中属性要使用变量要在前面加: -->
  15. <img :src="item.images.small" alt="">
  16. </div>
  17. </div>
  18. </template>

二、Axios请求数据

2-1 安装依赖

  1. yarn add axios -S

2-2 配置

  1. //main.js下
  2. import axios from 'axios'
  3. axios.defaults.baseURL = "https://music.aityp.com"; //主地址
  4. Vue.prototype.axios = axios;

2-3 获取数据

  1. <Item :data="value" v-for="value of musics" :key="value.id"></Item>
  2. export default {
  3. name:"All",
  4. data(){
  5. return{
  6. musics:[]
  7. }
  8. },
  9. components:{
  10. Item
  11. },
  12. mounted(){
  13. this.axios.get("/top/playlist").then(res=>{
  14. this.musics = res.data.playlists
  15. })
  16. }
  17. }

2-4 渲染数据

  1. <div class="content-item" v-for="item of goodsList" :key="item.productName">
  2. <img :src="item.productImage" alt />
  3. <p class="productName">{{item.productName}}</p>
  4. <p>¥{{item.salePrice}}</p>
  5. <el-button @click="addCart(item.productId)" class="add" type="danger" plain>加入购物车</el-button>
  6. </div>

三、Fetch请求

MDN文档

  1. fetch("http://yapi.demo.qunar.com/mock/34614/")
  2. .then(function(response) {
  3. return response.json();
  4. })
  5. .then(function(myJson) {
  6. console.log(myJson);
  7. });