一、本地读取数据
1-1 读取数据
// data/carts.json
[
{
"isSelected": true,
"productCover": "https://img3.doubanio.com/view/subject/m/public/s33510542.jpg",
"productName": "纸上行舟",
"productInfo": "青年作者黎幺短篇小说首度结集",
"productPrice": 57,
"productCount": 3,
"id": "0001"
},
{
"isSelected": true,
"productCover": "https://img3.doubanio.com/view/subject/m/public/s33497735.jpg",
"productName": "我可能得抑郁症了!舟",
"productInfo": "青年作者黎幺短篇小说首度结集",
"productPrice": 54,
"productCount": 2,
"id": "0002"
},
{
"isSelected": true,
"productCover": "https://img3.doubanio.com/view/subject/m/public/s33474961.jpg",
"productName": "绕日飞行",
"productInfo": "驯马、飞行、成长、爱情",
"productPrice": 22,
"productCount": 3,
"id": "0003"
}
]
//index.html
<body>
<div id="app">
</div>
<script>
var vm = new Vue({
el: "#app",
data:{
products:[]
},
mounted(){
axios.get('./data/carts.json').then(res=>{
this.products = res.data
})
}
})
</script>
</body>
1-2 发送http请求
先跨域:npm i axios-jsonp-pro -S
import axios from 'axios-jsonp-pro';
//使用
mounted(){
var url = "https://douban.uieee.com/v2/movie/in_theaters";
axios.jsonp(url).then(res=>{
this.movies = res.subjects;
})
}
//数据渲染
<template>
<div id="app">
<div class="item" v-for="item of movies" :key="item.id">
<p>{{item.title}}</p>
<!-- 在vue中属性要使用变量要在前面加: -->
<img :src="item.images.small" alt="">
</div>
</div>
</template>
二、Axios请求数据
2-1 安装依赖
yarn add axios -S
2-2 配置
//main.js下
import axios from 'axios'
axios.defaults.baseURL = "https://music.aityp.com"; //主地址
Vue.prototype.axios = axios;
2-3 获取数据
<Item :data="value" v-for="value of musics" :key="value.id"></Item>
export default {
name:"All",
data(){
return{
musics:[]
}
},
components:{
Item
},
mounted(){
this.axios.get("/top/playlist").then(res=>{
this.musics = res.data.playlists
})
}
}
2-4 渲染数据
<div class="content-item" v-for="item of goodsList" :key="item.productName">
<img :src="item.productImage" alt />
<p class="productName">{{item.productName}}</p>
<p>¥{{item.salePrice}}</p>
<el-button @click="addCart(item.productId)" class="add" type="danger" plain>加入购物车</el-button>
</div>
三、Fetch请求
fetch("http://yapi.demo.qunar.com/mock/34614/")
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(myJson);
});