考试需求
- 通过
axios
请求知乎首页文章列表数据并绑定到List.vue
组件。
API | 接口地址 |
---|---|
文章列表 | public/static/data/list.json |
接口响应示例
- 首页布局样式与效果图保持一致。
主要考察vue axios的使用
main.js
在js中引入axios
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//加入两行代码
import axios from 'axios'
Vue.prototype.$axios=axios
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
router,
render: function(h) { return h(App) }
}).$mount('#app')
List.vue
用axios请求加载json文件,用v-for对数据进行循环渲染,以及v-bind渲染,初始化请求接口使用create方法
<template>
<div class="list">
<div v-for="item in info" :key="item.id" class="list-item" >
<img
class='list-pic'
:src="item.imgUrl"
/>
<div class="list-info">
<p class='title'>{{item.title}}</p>
<p class='desc'>{{item.desc}}</p>
</div>
</div>
</div>
</template>
<script>
export default {
created(){
this.$axios.get('./static/data/list.json').then(res=>{
this.info = res.data.data.listInfo;
})
},
data() {
return {
info:[]
};
}
};
</script>
<style scoped>
.list-item {
padding: 20px 0;
overflow: hidden;
border-bottom: 1px solid #dcdcdc;
}
.list-pic {
float: right;
width: 125px;
height: 100px;
display: block;
border-radius: 4px;
}
.list-info {
width: 500px;
float: left;
}
.title {
padding: 10px 0;
font-size: 18px;
font-weight: bold;
color: #333;
}
.desc {
line-height: 22px;
font-size: 13px;
color: #999;
}
</style>
写法二:
直接在List.vue中import axios
不知道为什么,要绑定 :key=“item.id”才会不报错
<template>
<div class="list">
<div
class="list-item" v-for="item in datalist" :key="item.id"
>
<img
class='list-pic'
:src='item.imgUrl'
/>
<div class="list-info">
<p class='title'>{{item.title}}</p>
<p class='desc'>{{item.desc}}</p>
</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
datalist:[]
};
},
created(){
this.getList()
},
methods:{
getList(){
axios.get('./static/data/list.json').then(res=>{
console.log(res.data.data.listInfo);
this.datalist=res.data.data.listInfo
})
}
}
};
</script>
<style scoped>
.list-item {
padding: 20px 0;
overflow: hidden;
border-bottom: 1px solid #dcdcdc;
}
.list-pic {
float: right;
width: 125px;
height: 100px;
display: block;
border-radius: 4px;
}
.list-info {
width: 500px;
float: left;
}
.title {
padding: 10px 0;
font-size: 18px;
font-weight: bold;
color: #333;
}
.desc {
line-height: 22px;
font-size: 13px;
color: #999;
}
</style>