api部分
//我是api-login页面,以下是固定写法
import Axios from '@/util/request' //引入axios拦截器
export const register = data => {
return Axios({ // 获取商品分类列表
method: 'post',
url: 'api/users/login/',
data
})
}
组件部分
//我是login组件
<template>
<div class="login">
<mt-field label="手机号" placeholder="请输入手机号" type="tel" v-model="form.mobile" ></mt-field>
<p>{{form.tel}}{{form.psd}}</p>
<mt-field label="密码" placeholder="请输入密码" type="password" v-model="form.password" ></mt-field>
<mt-button type="primary" size='large' class="m-t-10" @click="register()">登录</mt-button>
</div>
</template>
<script>
import { Field, Button } from 'mint-ui'
export default {
components: {
Field,
Button
},
data () {
return {
form: {
mobile: '',
password: ''
},
uid: null,
token: null
}
},
mounted () {
this.register()
},
methods: {
async register () {
let { status, message } = await this.$store.dispatch('register', this.$qs.stringify({'mobile': this.form.mobile, 'password': this.form.password}))//把mobile和password输入的值传给actions
if (status === 'fail') {
console.log(message)
return false
} //固定写法
this.uid = sessionStorage.getItem('uid') //本地存储uid
this.token = sessionStorage.getItem('token') //本地存储token
console.log('uid', this.uid)
console.log('token', this.token)
this.$router.push({path: '/'})//跳转到首页
}
}
}
</script>
stroe部分
//在store下新文件login.js
import { register } from '@/api/login' //引入 api
const CODE = 200
export default {
state: {
serverInfo: { // 服务端返回的信息
status: 'fail',
message: '接口调用失败'
},
uid: sessionStorage.getItem('uid')
},
actions: {
async register ({commit, state}, payload) {
console.log('commit', commit)
console.log('state', state)
console.log('register', payload)//组件传参,mobile=13634124377&password=zsm254480433
// let {data} = await register(payload) //把payload的值传接口
let data = await register(payload)
console.log('actions', data) //把payload的值传接口,data就是接口返回的数据
console.log('actions111', data.data)
commit('GLOBAL_RES', data.data) //接口里data.data的值传给mutations
return state.serverInfo
}
},
mutations: {
GLOBAL_RES (state, {code, message, data}) { //把data里code,message,data
console.log('mutations', data)
if (code !== CODE) {
state.serverInfo = {
status: 'fail',
message
}
return false
}
state.serverInfo = {
status: 'success',
data //data数据返回给login.vue组件
}
console.log('message', message)
console.log('data', data)
console.log('code', data.uid)
// this.$cookies.set('uid', data.uid)
// let aa = this.$cookies.get('uid')
//sessionStorage.setItem('uid', data.uid)
// sessionStorage.setItem('token', data.token)
}
}
}