我是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謝謝!
