2019.10.16 vue使用axios请求接口数据
1.首先下载安装axios
npm install --save axios
2.在项目main.js里引入下面代码
import axios from 'axios'
Vue.prototype.$http = axios
3.在需要用到axios的组建中<script 标签中引入如下代码
import axios from 'axios'
4组件methods中定义function
<template>
<p class="tabbar">
<p>首页</p >
<button v-on:click = 'goback'>获取数据</button>
<p class="new_wrap" v-for="items in item">
<p class="newcard">
<p>
<p>{{items.issuer_nickname}}.</p >
</p >
<p>
{{items.title}}
</p >
<p class="pic">
< img :src="items.cover">
</p >
</p >
<br>
</p >
</p >
</template>
<script>
export default {
name: 'tabbar',
data () {
return {
msg: 'Welcome to Your Vue.js App',
item: []
}
},
methods:{
goback:function(){
console.log('hah');
this.$http.get('url') //把url地址换成你的接口地址即可
.then(res => {
//this.request.response = res.data
this.item = res.data.data.item; //把取item的数据赋给 item: []中
console.log(res.data.data.item);
if (res.data.code == '0') {
console.log('haha');
}else{
alert('数据不存在');
}
})
.catch(err => {
alert('请求失败');
})
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
*{margin: 0;padding: 0;}
@function torem($px){//$px为需要转换的字号
@return $px / 100px * 1rem; //100px为根字体大小
}
ul{
width: 100%;
position: absolute;
bottom: 0;
li{
width: torem(187.5px);
float:left;
height: torem(98px);
text-align:center;
background: #ccc;
}
}
img{
width: torem(200px);
height: torem(200px);
}
</style>