使用vue框架时获取后台数据,将axios封装的代码:
一.首先在src新建utils文件夹再建index.js文件,在此做数据的封装.
import axios from 'axios';
// process.env.NODE_ENV环境
let baseURL;
if (process.env.NODE_ENV === 'development') {
baseURL = 'http://132.232.87.95:3000/api'
} else {
//生产地址
baseURL = '/xxxx'
}
// 配置baseUrl
const $http = axios.create({
baseURL,
})
export const get = (url, params) => {
params = params || {};
return new Promise((resolve, reject) => {
$http.get(url, {
params,
}).then(res => {
if (res.data.status === 0) {
resolve(res.data);
} else {
alert(res.data.msg);
}
}).catch(error => {
alert('网络异常');
})
});
}
export const post = (url, params) => {
params = params || {};
return new Promise((resolve, reject) => {
$http.post(url, params).then(res => {
if (res.data.status === 0) {
resolve(res.data);
} else {
alert(res.data.msg);
}
}).catch(error => {
alert('网络异常');
})
});
}
第二步到main.js 将封装函数导入.
import {get,post} from './utils/index'//文件路径自己看情况写
Vue.prototype.$http = {
get,
post
}
第三步在到需要使用后台数据的index.vue的页面中引用(如my里面的index.vue)
export default {
data() {
return {
cinemas: []
};
},
created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/cinema/getList";
const res = await this.$http.get(url);
this.cinemas = res.cinemas;
}
}
};
第四步渲染页面:
<div class="mg-t-15 bd-gray" v-for="(item,index) in cinemas" :key="index">
<div class="flex-sb">
<p class="f14 mg-l-15">{{item.name}}</p>
<p class="orangr f6 mg-r-15">
¥
<span class="f16">{{item.lowPrice/100}}</span>起
</p>
</div>
<div class="flex-sb mg-t-8 pd-b-15">
<p class="ell f12 gray mg-l-15">{{item.address}}</p>
<p class="gray f12 mg-r-15">{{item.Distance.toFixed(2)}}km</p>
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
cinemas: []
};
},
created() {
this.getFilmList();
},
methods: {
async getFilmList() {
const url = "/cinema/getList";
const res = await this.$http.get(url);
this.cinemas = res.cinemas;
}
}
};
</script>
网友评论