好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

Vue实现让页面加载时请求后台接口数据

让页面加载时请求后台接口数据

<template>
? <div class="hello">
? ? <div>
? ? ? {{title}}
? ? </div>
? ? <hr>
? ? <button @click="convert">点击获取数据</button>
? </div>
</template>

<script>
? import axios from 'axios'
? export default {
? ? name: 'HelloWorld',
? ? data() {
? ? ? return {
? ? ? ? title: "静态数据"
? ? ? }
? ? },
? ? //在这里调用ajax请求方法
? ? created(){
? ? ? this.convert();
? ? },
? ? methods: {
? ? ? convert: function () {
? ? ? ? axios.get("api/sysUser/getSomething").then(res => {
? ? ? ? ? this.title = res.data;
? ? ? ? })
? ? ? }
? ? }
? }
</script>

Vue请求后台数据几种方式

常用的为: vue-resource 、 axios 、 fetch-jsonp

1、vue-resource官方提供的vue的一个插件

①安装:在项目根目录进行安装:cnpm install vue-resource --save

save说明:将此插件名插入到pachage.json文件中,别人在使用时,直接npm install,就会安装package.json里的所配置的软件插件名称了。

②引入vue-resource

在main.js中引入这个插件,并使用这个插件

import VueResource from 'vue-resource'
Vue.use(VueResource );

③示例:

export default{
? ? ? ? data(){
? ? ? ? ? ? return {
?
? ? ? ? ? ? ? ? msg:'我是一个首页组件msg',
? ? ? ? ? ? ? ? flag:true,
? ? ? ? ? ? ? ? list:[]
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? methods:{
?
? ? ? ? ? ? getData(){
? ? ? ? ? ? ? ? ? ? //请求数据
?
? ? ? ? ? ? ? ? ? ? var api='http://HdhCmsTestphonegap100测试数据/appapi.php?a=getPortalList&catid=20&page=1';?
?
? ? ? ? ? ? ? ? ? ? this.$http.get(api).then((response)=>{
? ? ? ? ? ? ? ? ? ? ? ? console.log(response);
?
? ? ? ? ? ? ? ? ? ? ? ? //注意this指向?
? ? ? ? ? ? ? ? ? ? ? ? this.list=response.body.result;???
? ? ? ? ? ? ? ? ? ? },function(err){?
? ? ? ? ? ? ? ? ? ? ? ? ? ? console.log(err);?
? ? ? ? ? ? ? ? ? ? })
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? mounted(){ ?/*生命周期函数*/?
? ? ? ? ? ? ? ? this.getData();?
? ? ? ? }
? ? }

2、axios的使用

安装 cnpm  install  axios --save

哪里用哪里引入axios

import Axios from 'axios';
? ? export default{
? ? ? ? data(){
? ? ? ? ? ? return { ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? list:[]
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? methods:{
?
? ? ? ? ? ? getData(){
? ? ? ? ? ? ? ??
? ? ? ? ? ? ? ? var api='http://HdhCmsTestphonegap100测试数据/appapi.php?a=getPortalList&catid=20&page=1';
? ? ? ? ? ? ? ? Axios.get(api).then((response)=>{
? ? ? ? ? ? ? ? ? ? this.list=response.data.result;
? ? ? ? ? ? ? ? }).catch((error)=>{
? ? ? ? ? ? ? ? ? ? console.log(error);?
? ? ? ? ? ? ? ? })?
? ? ? ? ? ? }
? ? ? ? },
? ? ? ? mounted(){ ?/*生命周期函数*/
?
? ? ? ? ? ? this.getData();
? ? ? ? } ? ? ?
? ? }

3、fetch-jsonp不受跨域限制

安装 cnpm i fetch-jsonp -S

用法:在项目中引入

import ?fetchJsonp ?from ?fetch-jsonp
let domain=`http://api.douban测试数据/v2/movie/top250`
? ? ? ? fetch(this.domain,{
? ? ? ? ? ? start:0,
? ? ? ? ? ? count:20,
? ? ? ? ? ? method:'GET',
? ? ? ? ? ? mode:'no-cors'
? ? ? ? }).then(response=>{
? ? ? ? ? ? console.log(response)
? ? ? ? ? ? console.log(response.json())
? ? ? ? ? ? return response.json()
? ? ? ? }).then(res=>{
? ? ? ? ? ? console.log(res)
? ? ? ? }).catch(e=>{
? ? ? ? ? ? console.log(e)
? ? ? ? })

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。 

查看更多关于Vue实现让页面加载时请求后台接口数据的详细内容...

  阅读:36次