<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="//cdn.bootcss.com/element-ui/1.1.2/theme-default/index.css">
<script type="text/javascript" src="//cdn.bootcss.com/vue/2.3.4/vue.js"></script>
<script type="text/javascript" src="//cdn.bootcss.com/element-ui/1.1.2/index.js"></script>
<script type="text/javascript" src="//cdn.bootcss.com/vue-resource/1.3.4/vue-resource.min.js"></script>
<script type="text/javascript" src="//cdn.bootcss.com/vue-router/2.6.0/vue-router.js"></script>
<style>
.el-row {
margin-bottom: 20px;
&:last-child {
margin-bottom: 0;
}
}
.login-box {
margin-top:20%;
margin-left:40%;
}
</style>
</head>
<body>
<div class="login-box" id="app" >
<el-row>
<el-col :span="8">
<el-input id="name" v-model="name" placeholder="请输入帐号">
<template slot="prepend">帐号</template>
</el-input>
</el-col>
</el-row>
<el-row>
<el-col :span="8">
<el-input id="password" v-model="password" type="password" placeholder="请输入密码">
<template slot="prepend">密码</template>
</el-input>
</el-col>
</el-row>
<el-row>
<el-col :span="8">
<el-button id="login" v-on:click="check" style="width:100%" type="primary">登录</el-button>
</el-col>
</el-row>
</div>
</body>
<script type="text/javascript">
new Vue({
el : '#app',
data : {
name : '',
password : ''
},
methods : {
check : function(event){
this.$router.push('index');
//获取值
var name = this.name;
var password = this.password;
if(name == '' || password == ''){
this.$message({
message : '账号或密码为空!',
type : 'error'
})
return;
}
var data={
username:name,
password:password
};
this.$http.get("login",{
params:data
}).then(function (response) {
//成功后跳转到index界面
this.$router.push('index')
}).catch(function (response) {
console.error(response);
});
}
}
})
</script>
</html>
this.$router跳转不了,我调试一直提示undefined。不知这样写为何会导致跳转失败,求指导。
其中。在
$http
返回回调中,this
指向的是$http
对象而非Vue实例,有两个方法:方法1:在外部定义一个值指代Vue实例
方法2:使用ES6的箭头函数实现上下文穿透
Update
针对
$router
为空的情况,是因为没有在Vue初始化的时候注册vue-router组件。有几种方法:方法1:
方法2: