温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

前后端分离之VueJS前端的示例分析

发布时间:2021-08-23 14:32:53 来源:亿速云 阅读:119 作者:小新 栏目:web开发

这篇文章给大家分享的是有关前后端分离之VueJS前端的示例分析的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。

前言

前端用什么框架都可以,这里选择小巧的vuejs。

要实现的功能很简单:

1、登录功能,成功将服务器返回的token存在本地

2、使用带token的header访问服务器的一个资源

本次实验环境:

"dependencies": {
  "vue": "^2.2.1"
 },
 "devDependencies": {
  "babel-core": "^6.0.0",
  "babel-loader": "^6.0.0",
  "babel-preset-latest": "^6.0.0",
  "cross-env": "^3.0.0",
  "css-loader": "^0.25.0",
  "file-loader": "^0.9.0",
  "vue-loader": "^11.1.4",
  "vue-template-compiler": "^2.2.1",
  "webpack": "^2.2.0",
  "webpack-dev-server": "^2.2.0"
 }

开发IDE:Atom

首先建一个项目

使用webpack构建

/Atom# vue init webpack-simple vue-jwt-demo
...
/Atom# cd vue-jwt-demo/
/Atom/vue-jwt-demo# cnpm install
/Atom/vue-jwt-demo# npm run dev

安装插件

/Atom/vue-jwt-demo# cnpm install vue-router

/Atom/vue-jwt-demo# cnpm install vue-resource

整体目录

前后端分离之VueJS前端的示例分析

auth.js

完成token的存取

const SERVER_URL = 'http://localhost:8081'
const LOGIN_URL = SERVER_URL+'/login2'

export default{
  data:{
    authenticated:false
  },
  login(context,info){
    context.$http.post(LOGIN_URL,info).then(function(data){
      console.log(data.bodyText)
      localStorage.setItem('token',data.bodyText);
      this.authenticated = true
      //跳到home页
      this.$router.push('home')
    },function(err){
      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

程序入口:完成路由和初始化

import Vue from 'vue'
import App from './App.vue'
import Login from './component/Login.vue'
import Home from './component/Home.vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import auth from './auth/auth'

Vue.use(VueRouter)
Vue.use(VueResource)

//在启动APP时进行校验是否有token
auth.checkAuth()

const routes= [
  {
    path:'/',redirect:'/login'
  },
  {
    path:'/login',component:Login
  },
  {
    path:'/home',component:Home
  }
]

const router = new VueRouter({
  routes
})
new Vue({
 router,
 render: h => h(App)
}).$mount('#app')

App.vue

页面载体

<template>
 <div id="app">
  <h2>{{msg}}</h2>
  <router-view></router-view>
 </div>
</template>

<script>
export default {
 name: 'app',
 data () {
  return {
   msg: 'Vue前后端分离demo'
  }
 }
}
</script>

Login.vue

登录页面

<template>
 <div>
  <h3>登录</h3>
  <p>{{ error }}</p>
  <div>
   <input
    type="text"
    placeholder="Enter your username"
    v-model="info.username"
   >
  </div>
  <div>
   <input
    type="password"
    placeholder="Enter your password"
    v-model="info.password"
   >
  </div>
  <button @click="submit()">登录</button>
 </div>
</template>

<script>
import auth from '../auth/auth'

export default {

 data() {
  return {
   info: {
    username: '',
    password: ''
   },
   error: ''
  }
 },
 methods: {
  submit() {
   var info = {
    username: this.info.username,
    password: this.info.password
   }
   auth.login(this, info)
  }
 }
}
</script>

效果:丑是丑了点

前后端分离之VueJS前端的示例分析

Home.vue

主页面,访问一个获取邮箱的请求

<template>
 <div id="home">
  <h2>{{msg}}</h2>
  <button @click="getEmail()">Get Email</button>
  <h3>Email:{{email}}</h3>
 </div>
</template>

<script>
import auth from '../auth/auth'

export default {
 name: 'home',
 data () {
  return {
   msg: '欢迎您登录成功',
   email:''
  }
  },
  beforeCreate(){
    //如果没有token的话需要重新登录
     if(!auth.authenticated){
      this.$router.push('login')
    }
  },
  methods:{
    getEmail(){
      this.$http.get('http://localhost:8081/user/getEmail',{
        headers:auth.getAuthHeader()
      }).then(function(re){
        this.email = re.bodyText
      },function(){
        console.log("get email error")
      })
    }
  }
}
</script>

<style>
#app {
 font-family: 'Avenir', Helvetica, Arial, sans-serif;
 -webkit-font-smoothing: antialiased;
 -moz-osx-font-smoothing: grayscale;
 text-align: center;
 color: #2c3e50;
 margin-top: 60px;
}

h2, h3 {
 font-weight: normal;
}

a {
 color: #42b983;
}
</style>

对应在服务端:

@GetMapping("/getEmail")
  public String getEmail() {
    return "xxxx@qq.com";
  }

前后端分离之VueJS前端的示例分析

可看到浏览器的本地存储:

前后端分离之VueJS前端的示例分析

感谢各位的阅读!关于“前后端分离之VueJS前端的示例分析”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI