一、登录
1.登录(初始版)
# 登录接口
class Login(APIView):
def post(self, request):
response = MyResponse()
name = request.data.get('name')
pwd = request.data.get('pwd')
user = models.UserInfo.objects.filter(name=name, pwd=pwd).first()
if user:
import uuid
token = uuid.uuid4()
models.UserToken.objects.update_or_create(user=user, defaults={'token': token})
response.msg = '登录成功'
response.name = name
response.token = token
else:
response.msg = '用户名或密码不正确'
response.status = 101
return Response(response.get_dic)
// main.js
// 1.先把store导入main.js
import store from './store'
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
// store.js
// 2.配置全局变量
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
// state:全局变量
state: {
name: '',
token: '',
},
mutations: {
},
actions: {}
})
// Login.vue
// 3.使用全局变量
methods: {
login: function () {
let _this = this;
this.$http.request({
url: _this.$url + '/login/',
method: 'post',
data: {'name': _this.name, 'pwd': _this.pwd},
}).then(function (response) {
if (response.data.status == 100) {
//_this.$store.state.变量名
_this.$store.state.name = response.data.name;
_this.$store.state.token = response.data.token
location.href = '/'
}
})
}
},
注:把cookie存在全局变量中,每次新页面会导致全局变量重置,不能永久保存
2.登录(cookie)
import Vue from 'vue'
import Vuex from 'vuex'
import Cookie from 'vue-cookies'
// 安装vue-cookies: npm install vue-cookies
Vue.use(Vuex)
export default new Vuex.Store({
// state:全局变量
state: {
name: Cookie.get('name'),
token: Cookie.get('token'),
},
//mutations:方法
mutations: {
login: function (state, response) {
// 替换全局变量
state.name = response.name
state.token = response.token
// 往cookie中写数据
Cookie.set('name', response.data.name)
Cookie.set('token', response.data.token)
},
logout: function (state) {
state.name = '';
state.token = '';
Cookie.set('name', '');
Cookie.set('token', '')
},
},
actions: {}
})
methods: {
login: function () {
let _this = this;
this.$http.request({
url: _this.$url + '/login/',
method: 'post',
data: {'name': _this.name, 'pwd': _this.pwd},
}).then(function (response) {
// 调用store.js的方法:
// _this.$store.commit('方法名','参数')
if (response.data.status == 100) {
_this.$store.commit('login', response)
location.href = '/'
}
})
}
},