1:axios插件 请求数据
<template>
<div id="axiosinfo">
<!--axios 处理cross跨域 后台配置好的
1 cnpm install --save-dev axios
2 引入axios 到项目 或者组件
-->
<p>axios 请求数据</p>
</div>
</template>
<script>
//该组件要使用axios 引入 仅仅限于当前组件使用
import Axios from "axios";
export default {
name: "axiosinfo",
mounted() {
//使用axios请求
Axios.get("/getuser")
.then(res => {
//success
console.log(res.data.result);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log("最后执行的操作");
});
Axios.post("/gettable")
.then(res => {
//success
console.log(res.data.result);
})
.catch(error => {
console.log(error);
})
.finally(() => {
console.log("最后执行的操作");
});
/*//例如后台get的api接收前台的参数 post则不需要写params
Axios.get("",{
params:{
id:1,
name:"张三"
}
}).then((res)=>{
//success
console.log(res.data.result);
}).catch((error)=>{
console.log(error);
}).finally(()=>{
console.log("最后执行的操作");
});
//get传值
Axios.get("http://www/sunny.com/getdata?id=1&name=zhangsan").then((res)=>{
//success
console.log(res.data.result);
}).catch((error)=>{
console.log(error);
}).finally(()=>{
console.log("最后执行的操作");
});*/
},
methods: {
getData() {
//因为axios返回的是一个promise对象 使用es6中的async异步刷新函数
//可以直接写
async function getMenthod() {}
}
},
data() {
return {};
}
};
</script>
2:resource mockjs插件
<template>
<div id="resourceinfo">
<!--
1cnpm install --save-dev vue-resource
2配置项目里面使用
main.js
1cnpm install --save-dev mockjs
2配置mock数据文件
3引入mock到vue项目main.js
-->
<p>渲染数据</p>
<ul>
<li v-for="(item,index) in user" :key="index">
<span>{{item.name}}</span>
<span>{{item.sex}}</span>
<span>{{item.age}}</span>
</li>
</ul>
</div>
</template>
<script>
export default {
name: "resourceinfo",
mounted() {
//使用vue-resource 请求数据
//使用mock模拟后台数据
this.$http
.get("/getuser") //get post 方式请求
.then(res => {
//请求成功
this.user = res.body.result;
})
.catch(error => {
//请求失败
console.log(error);
});
this.$http.post("/gettable").then(
res => {
//请求成功
console.log(res.body.result);
},
err => {
console.log(err);
}
);
},
data() {
return {
user: null
};
}
};
</script>
在main.js 的配置
//引入 vue-resource
import vueResource from 'vue-resource'
//给vue使用 use 使用插件 使用中间件
Vue.use(vueResource);
//引入mockjs
require("./mock/mock");