我是vue菜鸟,第一次用vue做项目,写一些自己的理解,可能有些不正确,欢迎纠正。
vue开发环境要配置本地代理服务。把config文件加下的index.js里的dev添加一些内容,
dev: {env: require('./dev.env'),port: 8090,autoOpenBrowser: true,assetsSubDirectory: 'static',assetsPublicPath: '/',proxyTable: {'/api': {target: 'http://xxxxxxxxxx.xxx',//这里是服务器地址额changeOrigin: true,pathRewrite: {'^/api': ''//这里理解成用‘/api’代替target里面的地址,后面组件中我们掉接口时直接用api代替 比如我要调用'http://40.00.100.100:3002/user/add',直接写‘/api/user/add’即可}}},
然后就是在main.js文件里添加一下内容:
import axios from 'axios'
Vue.prototype.$axios=axios;
然后呢就是在src文件夹里创建一个api文件夹,在api文件夹中创建一个api.js文件,在里边简单的处理请求一下是我写的:
//说明一下"/api/api"第一个api是vue接口代理必须要添加的,第二个api是因为我们后台给的接口是api开头的
/*post请求*/
export const getUserListPage = params => { return axios.post('/api/api/user/UserList', params).then(res => res.data); };
/*get请求*/
export const addUser = params => { return axios.get('/api/api/user/addUser', { params: params }); };
最后你就可以在要用到接口的.vue文件里使用了
首先要引入
import {getUserListPage,addUser} from '../../api/getData'
然后在调用
methods: {//获取用户列表getUsers() {let para = {page: this.page,name: this.filters.name};this.listLoading = true;getUserListPage(para).then((res) => {this.total = res.data.total;console.log(res.data.total);this.users = res.data.users;console.log(res.data);this.listLoading = false;}).catch((err) => {console.log(err);});},addSubmit: function () {this.$refs.editForm.validate((valid) => {if (valid) {this.$confirm('确认提交吗?', '提示', {}).then(() => {this.editLoading = true;let para = Object.assign({}, this.editForm);para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');addUser(para).then((res) => {this.editLoading = false;this.$message({message: '提交成功',type: 'success'});this.$refs['editForm'].resetFields();this.editFormVisible = false;this.getUsers();});});}});},
}
第一次使用vue做项目,若发现错误请大神留言纠正,O(∩_∩)O谢谢!