爬过得那些坑
前言:在整个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.useruser代表的参数名,不但可以传递单个参数,也可以传递对应,解析的方式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>版权声明
本文仅代表作者观点,不代表百度立场。
本文系作者授权百度百家发表,未经许可,不得转载。




