vue登錄界面---太簡單
<template> <div class="login"> <input placeholder="請輸入用戶名" v-model="info.username"> <input placeholder="請輸入密碼" v-model="info.password"> <button @click='submit()'>登錄</button> </div> </template> <script> import auth from '../../auth/auth' export default { data () { return { info:{ username: 'zhangsan', password: '123456' } }; }, methods: { submit() { console.log(this.info); var info = { username: this.info.username, password: this.info.password } auth.login(this,info) } } }; </script> <style > </style>
anth.js
const SERVER_URL = 'http://localhost:8081' const LOGIN_URL = SERVER_URL+'/login' export default{ data:{ authenticated:false }, login(context,info){ context.$http.post(LOGIN_URL,info).then((data)=>{ //alert('success') console.log(data.bodyText) localStorage.setItem('token',data.bodyText); this.authenticated = true //跳到home頁 context.$router.push('userInfo') },(err)=>{ // alert('loser') console.log(err+","+err.body.message) context.error = err.body.message }) }, getAuthHeader(){ return { 'Authorization':'Bearer '+localStorage.getItem('token') } }, checkAuth(){ var token = localStorage.getItem('token') if(token){ this.authenticated = true }else{ this.authenticated = false } } }
main.js
// The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' //import router from './router' import VueResource from 'vue-resource' import VueRouter from 'vue-router' import Login from './views/login/login.vue' import UserInfo from './views/login/user_info.vue' import auth from './auth/auth' Vue.config.productionTip = false Vue.use(VueResource); Vue.use(VueRouter); auth.checkAuth() const routes= [ { path:'/',redirect:'/login' }, { path:'/login',component:Login }, { path:'/userInfo',component:UserInfo } ] const router = new VueRouter({ routes })
//這兩個需要設置,不然前端向后台不能傳遞數據 Vue.http.options.emulateJSON = true Vue.http.options.emulateHTTP = true new Vue({ router, render: h => h(App) }).$mount('#app')
注意:這里在main.js里面添加了兩行
Vue.http.options.emulateJSON = true
Vue.http.options.emulateHTTP = true
加上這兩行,表示JSON和HTTP的數據格式可以傳給后台。
不然報錯,我之前沒有這兩行都是報這樣的錯

