天天看點

前後端分離之Vue(三)爬過得那些坑爬過得那些坑

爬過得那些坑

前言:在整個Vue的過程中,遇到了不少坑。查找不同的資料,把這些坑給填了,記錄下這些坑,以及解決辦法。

一、Http請求的那些坑

1.不支援http請求

表現為:程式啟動正常,點選按妞不跳轉,背景無響應,浏覽器調試出現

Uncaught TypeError: Cannot read property 'post' of undefined           

解決辦法:添加vue-resource支援,在main.js添加

import VueResource from 'vue-resource'

Vue.use(VueResource);

2.post請求,背景接收參數為null

表現為:背景響應但是參數為null,正确的登陸失效,調試時,參數為from object

解決辦法:http請求中,添加

{emulateJSON:true}           

全部的Http請求部分代碼為

_this.$http.post('http://localhost:8080/person/login', {

username: _this.username,

password: _this.password

}

,{emulateJSON:true}

)

.then(function (response) {

var errorcode = response.data.code;

if (errorcode == "200") {

_this.$router.push(

{ path: '/HelloWorld',

query: {

user: response.data.data,

}

});

} else {

_this.$router.push({ path: '/Fail' });

}

})

.catch(function (error) {

console.log(error);

});

3、正确處理後,跳轉到空頁面

原因:路由的url配置有問題,注意元件的引用的對應關系以及path的路徑問題

4.Request請求變成Options

解決辦法:設定頭格式

http: {

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

},

二、Vue視圖之間的跳轉實作

1.引用router元件

2.在router.js添加對應的view,以及相對應的path的配置

3.this.$router.push({path:'url'})

4.可參照上文的Http請求部分代碼

三、Vue跳轉傳遞參數

采用程式設計式的實作方式

傳遞參數

_this.$router.push(

{ path: '/HelloWorld',//跳轉的路徑

query: {//query 代表傳遞參數

user: response.data.data,//參數名key,以及對應的value

}

});

接收參數

this.$route.query.user           

user代表的參數名,不但可以傳遞單個參數,也可以傳遞對應,解析的方式user.屬性

四、執行個體,登陸頁面的Vue代碼

<template>

<div class="login">

{{ message }}<br/>

<input v-model="username" placeholder="使用者名"><br/>

<input v-model="password" placeholder="密碼"><br/>

<button v-on:click="login">登陸 </button>

</div>

</template>

<script>

export default {

name: "login",

data() {

return {

message: 'Vue 登陸頁面',

username: '',

password: ''

}

},

http: {

headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'}

},

methods: {

login: function () {

var _this = this;

console.log(_this.username+_this.password);

_this.$http.post('http://localhost:8080/person/login', {

username: _this.username,

password: _this.password

}

,{emulateJSON:true}

)

.then(function (response) {

var errorcode = response.data.code;

if (errorcode == "200") {

_this.$router.push(

{ path: '/HelloWorld',

query: {

user: response.data.data,

}

});

} else {

_this.$router.push({ path: '/Fail' });

}

})

.catch(function (error) {

console.log(error);

});

}

}

}

</script>

<style scoped>

</style>

本文作者:shenbug

本文釋出時間:2018年03月13日

本文來自雲栖社群合作夥伴

CSDN

,了解相關資訊可以關注csdn.net網站。

上一篇: css loading
下一篇: 電影院插件

繼續閱讀