您的位置:首页 > 产品设计 > UI/UE

vue-cli,vue-axios登录注册实例 (后台flask实现,数据库sqlite3)并在iphone模拟器中运行

2017-11-16 15:09 1541 查看
最近在学vue,看一个教程,教程中用vue-resource发请求,不过因为这个插件已经不更新了所以我改用vue-axios,教程的后台是用php写的,源码我没有看,我自己用flask实现了一个后台

原教程地址:https://segmentfault.com/a/1190000009329619

原教程github代码:https://github.com/yicenburan/manage

先用vue -cli创建项目

vue init webpack logindemo

cd logindemo

cnpm install


cnpm install --save axios vue-axios


目录结构:






红色框内是需要自己手动添加的目录与文件

main.js 添加:

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios, axios)


先做登入,views/login/login.vue


<template>
<div>
<div class="login-wrap" v-show="showLogin">
<h3>登录</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="username">
<input type="password" placeholder="请输入密码" v-model="password">
<button v-on:click="login">登录</button>
<span v-on:click="ToRegister">没有账号?马上注册</span>
</div>

<div class="register-wrap" v-show="showRegister">
<h3>注册</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="newUsername">
<input type="password" placeholder="请输入密码" v-model="newPassword">
<button v-on:click="register">注册</button>
<span v-on:click="ToLogin">已有账号?马上登录</span>
</div>
</div>
</template>

<style>
.login-wrap{text-align:center;}
input{display:block; width:250px; height:40px; line-height:40px; margin:0 auto; margin-bottom: 10px; outline:none; border:1px solid #888; padding:10px; box-sizing:border-box;}
p{color:red;}
button{display:block; width:250px; height:40px; line-height: 40px; margin:0 auto; border:none; background-color:#41b883; color:#fff; font-size:16px; margin-bottom:5px;}
span{cursor:pointer;}
span:hover{color:#41b883;}
</style>

<script>
export default{
data(){
return{
showLogin: true,
showRegister: false,
showTishi: false,
tishi: '',
username: '',
password: '',
newUsername: '',
newPassword: ''
}
}
}
</script>


配置路由,src/router/router.js


import Vue from 'vue'
import Router from 'vue-router'
/*引入页面*/
import Login from '@/views/login/login.vue'
import Main from '@/views/main/main.vue'
import Home from '@/views/home/home.vue'

Vue.use(Router)

/*配置路由*/
export default new Router({
routes: [
{
path: '/',
name: 'Login',
component: Login
},
{
path: '/main',
name: 'Main',
component: Main
},
{
path: '/home',
name: 'Home',
component: Home
}
]
})


使用cnpm run dev启动项目






cookie操作,src/assets/js/cookie.js


/*用export把方法暴露出来*/
/*设置cookie*/
export function setCookie(c_name,value,expire) {
var date=new Date()
// 这个是cookie有效期,将cookie的有效时间设成当前时间之前就是删除
date.setSeconds(date.getSeconds()+expire)
document.cookie=c_name+ "="+escape(value)+"; expires="+date.toGMTString()
console.log(document.cookie)
}

/*获取cookie*/
export function getCookie(c_name){
if (document.cookie.length>0){
let c_start=document.cookie.indexOf(c_name + "=")
if (c_start!=-1){
c_start=c_start + c_name.length+1
let c_end=document.cookie.indexOf(";",c_start)
if (c_end==-1) c_end=document.cookie.length
return unescape(document.cookie.substring(c_start,c_end))
}
}
return ""
}

/*删除cookie*/
export function delCookie(c_name){
setCookie(c_name, "", -1)
}


修改login.vue,有些代码注释是为了当前测试


<template>
<div>
<div class="login-wrap" v-show="showLogin">
<h3>登陆</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="username"/>
<input type="password" placeholder="请输入密码" v-model="password"/>
<button v-on:click="login">登入</button>
<!--<span v-on:click="ToRegister">没有账号?马上注册</span>-->
</div>
<!--<div class='register-wrap' v-show="showRegister">
<h3>注册</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="newUsername"/>
<input type="text" placeholder="请输入密码" v-model="newPassword" />
<button v-on:click="register">注册</button>
<span v-on:click="ToLogin">已有账号?马上登入</span>
</div>-->
</div>
</template>

<script>
import {setCookie,getCookie} from '../../assets/js/cookie.js'
export default{
data(){
return{
username: '',
password: '',
newUsername: '',
newPassword: '',
tishi: '',
showTishi: false,
showLogin: true,
showRegister: false
}
},
mounted(){
if(getCookie("username")){
this.$router.push('/home')
}
},
methods:{
login(){
if(this.username==""||this.password==""){
alert("请输入用户名或者密码")
}else{
// URLSearchParams对象是为了让参数以form data形式
let params = new URLSearchParams();
params.append('username', this.username);
params.append('password', this.password);
this.axios.post("http://127.0.0.1:5000/login",params).then((res)=>{
console.log(res.data)
console.log(typeof res.data)
if(res.data==-1){
this.tishi = " 该用户不存在"
this.showTishi = true
}else if(res.data == 0){
this.tishi = "密码输入错误"
this.showTishi = true
}else if(res.data == "admin"){
this.$router.push("/main")
}else{
this.tishi = "登入成功"
this.showTishi = true
setCookie("username",this.username,1000*60)
setTimeout(function(){
this.$router.push("/home")
}.bind(this),1000)
}
})
}
}
}
}
</script>

<style>
.login-wrap{text-align:center;}
input{display:block; width:250px; height:40px; line-height:40px; margin:0 auto; margin-bottom: 10px; outline:none; border:1px solid #888; padding:10px; box-sizing:border-box;}
p{color:red;}
button{display:block; width:250px; height:40px; line-height: 40px; margin:0 auto; border:none; background-color:#41b883; color:#fff; font-size:16px; margin-bottom:5px;}
span{cursor:pointer;}
span:hover{color:#41b883;}
</style>


src/views/home/home.vue


<template>
<div>
<h3>欢迎{{name}}</h3>
<!-- 教程中href是#,但是我测试注销后不能自动跳到 -->
<a href="/" v-on:click="quit">注销登入</a>
</div>
</template>

<script>
import {setCookie,getCookie,delCookie} from '../../assets/js/cookie.js'
export default{
data(){
return{
name:""
}
},
mounted(){
let uname = getCookie("username")
this.name = uname
if(uname == ""){
this.$router.push("/")
}
},
methods:{
quit(){
delCookie("username")
}
}
}
</script>

<style>
</style>


后台程序;






sqltest.py:

# -*-coding:utf-8 -*-

__author__ = "ZJL"

import sqlite3

# cx = sqlite3.connect("mydb.db",check_same_thread=False)
# cu = cx.cursor()
# cu.execute('create table mydb (id integer primary key,username varchar(50),password varchar(50))')
# cu.close()
#
# cu.execute("insert into mydb values(null, 'jay', '123456')")
# cu.execute("insert into mydb values(null, 'abc', '123')")
# cx.commit()

# cu.execute("select password from mydb where username='jay'")
# res = cu.fetchone()
# print(res)

# 线以下的全部注视掉,放开上面的所有注释就是建表,插入数据
# -----------------------------------------

class sqlT(object):
def __init__(self,dbname):
self.cx = sqlite3.connect(dbname,check_same_thread=False)
self.cu = self.cx.cursor()

def getdata(self,usernx):
sql = "select password from 'mydb' where username=\'"+usernx+"\'"
self.cu.execute(sql)
ress = self.cu.fetchone()
if ress:
return ress
else:
return ()


loginpy.py:

from flask import Flask
from flask import request
from sqltest import sqlT
import sys
from flask_cors import *

DATABASE = sys.path[0]+'/mydb.db'
app = Flask(__name__)
# 跨域解决方案
CORS(app, supports_credentials=True)
ss = sqlT(DATABASE)

@app.route('/')
def hello_world():
return 'Hello World!'

@app.route("/login", methods=['POST'])
def login():
if request.method == 'POST' and request.form.get('username') and request.form.get('password'):
datax = request.form.to_dict()
usernamx = datax.get("username")
passwordx = datax.get("password")
print(usernamx,passwordx)
res = ss.getdata(usernamx)
if not res:
print("-1")
return "-1"
elif passwordx != res[0]:
print("0")
return "0"
elif usernamx=="admin" and passwordx == res[0]:
print("admin")
return "admin"
else:
return "1"
else:
return "cccc"

if __name__ == '__main__':
app.run(debug=True)






















管理页面,src/views/main/main.vue


<template>
<div>
<h3>所有注册用户</h3>
<ul>
<li v-for="item in list">
{{item.username}}
</li>
</ul>
<a href="/" v-on:click="quit">注销登入</a>
</div>
</template>

<script>
export default{
data(){
return{
list:""
}
},
mounted(){
this.axios.get("http://127.0.0.1:5000/main").then(
(res)=>{
this.list = res.data
console.log(res)
console.log(res.data)
}
)
},
methods:{
quit(){
delCookie("username")
}
}
}
</script>

<style>
ul{padding: 0;}
ul li{list-style: none;}
</style>


修改sqltest.py:

# -*-coding:utf-8 -*-

__author__ = "ZJL"

import sqlite3

# cx = sqlite3.connect("mydb.db",check_same_thread=False)
# cu = cx.cursor()
# cu.execute('create table mydb (id integer primary key,username varchar(50),password varchar(50))')
# cu.close()
#
# cu.execute("insert into mydb values(null, 'jay', '123456')")
# cu.execute("insert into mydb values(null, 'abc', '123')")
# cx.commit()

# cu.execute("select password from mydb where username='jay'")
# res = cu.fetchone()
# print(res)

# 线以下的全部注视掉,放开上面的所有注释就是建表,插入数据
# -----------------------------------------

class sqlT(object):
def __init__(self,dbname):
self.cx = sqlite3.connect(dbname,check_same_thread=False)
self.cu = self.cx.cursor()

def getdata(self,usernx):
sql = "select password from 'mydb' where username=\'"+usernx+"\'"
self.cu.execute(sql)
ress = self.cu.fetchone()
if ress:
return ress
else:
return ()def getdataall(self):
sql = "select username from 'mydb'"
self.cu.execute(sql)
ress = self.cu.fetchall()
lists = []
for res in ress:
lists.append({"username":res[0]})
return lists



修改loginpy.py

from flask import Flask
from flask import request
from sqltest import sqlT
import sys
from flask_cors import *
import json

DATABASE = sys.path[0]+'/mydb.db'
app = Flask(__name__)
CORS(app, supports_credentials=True)
ss = sqlT(DATABASE)

@app.route('/')
def hello_world():
return 'Hello World!'

@app.route("/login", methods=['POST'])
def login():
if request.method == 'POST' and request.form.get('username') and request.form.get('password'):
datax = request.form.to_dict()
usernamx = datax.get("username")
passwordx = datax.get("password")
print(usernamx,passwordx)
res = ss.getdata(usernamx)
if not res:
print("-1")
return "-1"
elif passwordx != res[0]:
print("0")
return "0"
elif usernamx=="admin" and passwordx == res[0]:
print("admin")
return "admin"
else:
return "1"
else:
return "cccc"

@app.route("/main",methods=["GET"])
def getmain():
if request.method == 'GET':
res = ss.getdataall()
xx = json.dumps(res)
return xx

if __name__ == '__main__':
app.run(debug=True)



login.vue页面控制登录注册切换,[b]修改login.vue
[/b]

<template>
<div>
<div class="login-wrap" v-show="showLogin">
<h3>登陆</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="username"/>
<input type="password" placeholder="请输入密码" v-model="password"/>
<button v-on:click="login">登入</button>
<span v-on:click="ToRegister">没有账号?马上注册</span>
</div>
<div class='register-wrap' v-show="showRegister">
<h3>注册</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="newUsername"/>
<input type="text" placeholder="请输入密码" v-model="newPassword" />
<!-- <button v-on:click="register">注册</button> -->
<span v-on:click="ToLogin">已有账号?马上登入</span>
</div>
</div>
</template>

<script>
import {setCookie,getCookie} from '../../assets/js/cookie.js'
export default{
data(){
return{
username: '',
password: '',
newUsername: '',
newPassword: '',
tishi: '',
showTishi: false,
showLogin: true,
showRegister: false
}
},
mounted(){
if(getCookie("username")){
this.$router.push('/home')
}
},
methods:{
login(){
if(this.username==""||this.password==""){
alert("请输入用户名或者密码")
}else{
let params = new URLSearchParams();
params.append('username', this.username);
params.append('password', this.password);
this.axios.post("http://127.0.0.1:5000/login",params).then((res)=>{
console.log(res.data)
console.log(typeof res.data)
if(res.data==-1){
//                          alert("aaaaa")
this.tishi = " 该用户不存在"
this.showTishi = true
}else if(res.data == 0){
this.tishi = "密码输入错误"
this.showTishi = true
}else if(res.data == "admin"){
this.$router.push("/main")
}else{
this.tishi = "登入成功"
this.showTishi = true
setCookie("username",this.username,1000*60)
setTimeout(function(){
this.$router.push("/home")
}.bind(this),1000)
}
})
}
},
ToRegister(){
this.showRegister = true
this.showLogin = false
},
ToLogin(){
this.showRegister = false
this.showLogin = true
}

}
}
</script>

<style>
.login-wrap{text-align:center;}
input{display:block; width:250px; height:40px; line-height:40px; margin:0 auto; margin-bottom: 10px; outline:none; border:1px solid #888; padding:10px; box-sizing:border-box;}
p{color:red;}
button{display:block; width:250px; height:40px; line-height: 40px; margin:0 auto; border:none; background-color:#41b883; color:#fff; font-size:16px; margin-bottom:5px;}
span{cursor:pointer;}
span:hover{color:#41b883;}
</style>


注册功能,修改login.vue

<template>
<div>
<div class="login-wrap" v-show="showLogin">
<h3>登陆</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="username"/>
<input type="password" placeholder="请输入密码" v-model="password"/>
<button v-on:click="login">登入</button>
<span v-on:click="ToRegister">没有账号?马上注册</span>
</div>
<div class='register-wrap' v-show="showRegister">
<h3>注册</h3>
<p v-show="showTishi">{{tishi}}</p>
<input type="text" placeholder="请输入用户名" v-model="newUsername"/>
<input type="text" placeholder="请输入密码" v-model="newPassword" />
<button v-on:click="register">注册</button>
<span v-on:click="ToLogin">已有账号?马上登入</span>
</div>
</div>
</template>

<script>
import {setCookie,getCookie} from '../../assets/js/cookie.js'
export default{
data(){
return{
username: '',
password: '',
newUsername: '',
newPassword: '',
tishi: '',
showTishi: false,
showLogin: true,
showRegister: false
}
},
mounted(){
if(getCookie("username")){
this.$router.push('/home')
}
},
methods:{
login(){
if(this.username==""||this.password==""){
alert("请输入用户名或者密码")
}else{
let params = new URLSearchParams();
params.append('username', this.username);
params.append('password', this.password);
this.axios.post("http://127.0.0.1:5000/login",params).then((res)=>{
console.log(res.data)
console.log(typeof res.data)
if(res.data==-1){
//                          alert("aaaaa")
this.tishi = " 该用户不存在"
this.showTishi = true
}else if(res.data == 0){
this.tishi = "密码输入错误"
this.showTishi = true
}else if(res.data == "admin"){
this.$router.push("/main")
}else{
this.tishi = "登入成功"
this.showTishi = true
setCookie("username",this.username,1000*60)
setTimeout(function(){
this.$router.push("/home")
}.bind(this),1000)
}
})
}
},
ToRegister(){
this.showRegister = true
this.showLogin = false
},
ToLogin(){
this.showRegister = false
this.showLogin = true
},
register(){
if(this.newUsername==""||this.newPassword==""){
alert("请输入用户名或者密码")
}else{
let params = new URLSearchParams();
params.append('username', this.newUsername);
params.append('password', this.newPassword);
this.axios.post("http://127.0.0.1:5000/register",params).then((res)=>{
console.log(res)
console.log(res.data)
if(res.data=="OK"){
this.tishi = "注册成功"
this.showTishi = true
this.newUsername=""
this.newPassword=""
setTimeout(function(){
this.showRegister = false
this.showLogin = true
this.showTishi = false
}.bind(this),1000)
}
})
}
}

}
}
</script>

<style>
.login-wrap{text-align:center;}
input{display:block; width:250px; height:40px; line-height:40px; margin:0 auto; margin-bottom: 10px; outline:none; border:1px solid #888; padding:10px; box-sizing:border-box;}
p{color:red;}
button{display:block; width:250px; height:40px; line-height: 40px; margin:0 auto; border:none; background-color:#41b883; color:#fff; font-size:16px; margin-bottom:5px;}
span{cursor:pointer;}
span:hover{color:#41b883;}
</style>


修改sqltest.py

# -*-coding:utf-8 -*-

__author__ = "ZJL"

import sqlite3

# cx = sqlite3.connect("mydb.db",check_same_thread=False)
# cu = cx.cursor()
# cu.execute('create table mydb (id integer primary key,username varchar(50),password varchar(50))')
# cu.close()
#
# cu.execute("insert into mydb values(null, 'jay', '123456')")
# cu.execute("insert into mydb values(null, 'abc', '123')")
# cx.commit()

# cu.execute("select password from mydb where username='jay'")
# res = cu.fetchone()
# print(res)

class sqlT(object):
def __init__(self,dbname):
self.cx = sqlite3.connect(dbname,check_same_thread=False)
self.cu = self.cx.cursor()

def getdata(self,usernx):
sql = "select password from 'mydb' where username=\'"+usernx+"\'"
self.cu.execute(sql)
ress = self.cu.fetchone()
if ress:
return ress
else:
return ()

def getdataall(self):
sql = "select username from 'mydb'"
self.cu.execute(sql)
ress = self.cu.fetchall()
lists = []
for res in ress:
lists.append({"username":res[0]})
return lists

def setdata(self,usern,passw):
sql = "insert into 'mydb'(username,password) values( \'%s\', \'%s\')"%(usern,passw)
self.cu.execute(sql)
self.cx.commit()
return 0

# ss = sqlT("mydb.db")
# print(ss.getdata("admin"))
# print(ss.getdataall())


修改loginpy.py:

from flask import Flask
from flask import request
from sqltest import sqlT
import sys
from flask_cors import *
import json

DATABASE = sys.path[0]+'/mydb.db'
app = Flask(__name__)
CORS(app, supports_credentials=True)
ss = sqlT(DATABASE)

@app.route('/')
def hello_world():
return 'Hello World!'

@app.route("/login", methods=['POST'])
def login():
if request.method == 'POST' and request.form.get('username') and request.form.get('password'):
datax = request.form.to_dict()
usernamx = datax.get("username")
passwordx = datax.get("password")
print(usernamx,passwordx)
res = ss.getdata(usernamx)
if not res:
print("-1")
return "-1"
elif passwordx != res[0]:
print("0")
return "0"
elif usernamx=="admin" and passwordx == res[0]:
print("admin")
return "admin"
else:
return "1"
else:
return "cccc"

@app.route("/main",methods=["GET"])
def getmain():
if request.method == 'GET':
res = ss.getdataall()
xx = json.dumps(res)
return xx

@app.route("/register",methods=["POST"])
def register():
if request.method == 'POST' and request.form.get('username') and request.form.get('password'):
datax = request.form.to_dict()
usernamx = datax.get("username")
passwordx = datax.get("password")
res = ss.setdata(usernamx,passwordx)
if res==0:
return "OK"
else:
return "NO"
else:
return "no"

if __name__ == '__main__':
app.run(debug=True)




打包的时候会产生map文件,比较占空间,修改config/index.js

productionSourceMap: false,


改成false

cd logindemo

cnpm run build


你会看到一个dist目录

用hbuilder编辑器新建一个空白的移动项目,将dist里面的index.html和static目录复制新建的移动项目中,覆盖掉原有的index.html






这时候需要需改index.html

因为 css文件路径是href=/static/css/app....css改成[b]static/css/app....css
[/b]

js同理,从src=/static/js/app.e3b84...js改成[b]static/js/app.e3b84...js[/b]



修改所有js文件,因为代码压缩缘故,我们用编辑器的替换功能,将所有click替换成touchstart,我试了click事件有些点击不能用

mac电脑打开xcode

然后会发现[b]hbuilder中运行=》真机运行 中多了iPhone模拟器,选择一个模拟器[/b]






这样就可以正常使用了,不过使用中出现一个问题就是登入以后的注销不能跳转到登入界面

这里只需将views/home/home.vue

<template>
<div>
<h3>欢迎{{name}}</h3>
<a href="/" v-on:click="quit">注销登入</a>
</div>
</template>

<script>
import {setCookie,getCookie,delCookie} from '../../assets/js/cookie.js'
export default{
data(){
return{
name:""
}
},
mounted(){
let uname = getCookie("username")
this.name = uname
if(uname == ""){
this.$router.push("/")
}
},
methods:{
quit(){
delCookie("username")
//添加这一句
this.$router.push("/")
}
}
}
</script>

<style>
</style>
添加一句
this.$router.push("/")
然后重新打包,重新部署就可以了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: