vue-cli,vue-axios登入註冊例項 (後臺flask實現,資料庫sqlite3)並在iphone模擬器中執行
最近在學vue,看一個教程,教程中用vue-resource發請求,不過因為這個外掛已經不更新了所以我改用vue-axios,教程的後臺是用php寫的,原始碼我沒有看,我自己用flask實現了一個後臺
先用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頁面控制登入註冊切換,修改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
}
}
}
</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改成static/css/app....css
js同理,從src=/static/js/app.e3b84...js改成static/js/app.e3b84...js
修改所有js檔案,因為程式碼壓縮緣故,我們用編輯器的替換功能,將所有click替換成touchstart,我試了click事件有些點選不能用
mac電腦開啟xcode
然後會發現hbuilder中執行=》真機執行 中多了iPhone模擬器,選擇一個模擬器
這樣就可以正常使用了,不過使用中出現一個問題就是登入以後的登出不能跳轉到登入介面
這裡只需將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("/")
然後重新打包,重新部署就可以了