npm install --global vue-cli
vue init webpack my-project
這樣就構建了一個本地vue項目vue
結下來,如何調用後端接口呢?webpack
安裝 vue-resource web
npm i vue-resource --save
在main.js裏面加入如下代碼
import VueResource from 'vue-resource'
Vue.use(VueResource)
Vue.http.options.emulateJSON = true; //http請求設置
Vue.http.options.headers = {
'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8' //http請求頭設置form表單提交
};
找到src\components\Hello.vue 把下面代碼替換原來的,加入了表單,點擊登陸,調用後端的接口vue-cli
<template> <div> <div> <input type="text" placeholder="Enter your username" v-model="info.username" > </div> <div> <input type="password" placeholder="Enter your password" v-model="info.password" > </div> <button @click="submit()">登陸</button> </div> </template> <script> export default { data () { return { info: { username: '', password: '' } } }, methods: { submit () { var info = { data:JSON.stringify( { username: this.info.username, password: this.info.password } ) } this.$http.post('/api/user/login', info).then(function (data) { console.log(data.data) }, function (err) { console.log(err) }) } } } </script>
因爲後端的接口域名是是www.bobomusic.com/api/,post請求裏面的接口域名實際上是localhost:8080/api/, 這樣是調用不到的,怎麼辦呢?npm
vue的config\index.js裏面能夠設置反向代理到後端的接口域名,打開index.js,加入以下圖裏面紅色框的一段代碼後端
'/api': {
target: 'http://www.bobomusic.com/api',
changeOrigin: true,
pathRewrite: {
'^/api': ''
}
}
而後在頁面點擊登陸按鈕,調用成功,返回的數據以下圖:api