Spring and Vue(前后端分离)

一. 创建一个Vue项目(可以使用webpack创建,也可以使用Vue-cli创建),修改src/components/HelloWorld.vue

<template>
  <div class="hello">
    <h1>Welcome {
         
  { title }}</h1>
    <p>Id: <span>{
         
  {greeting.id}}</span></p>
    <p>Message: <span>{
         
  {greeting.content}}!</span></p>
  </div>
</template>

<script>
export default {
  name: HelloWorld,
  data () {
    return {
      title: Hello world,
      greeting: {
        id: XXX,
        content: Hello World
      }
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h1 {
  font-weight: normal;
}
</style>

在CMD中进入该项目目录,执行npm run dev,运行之后,在浏览器访问

二. 新建一个Spring项目,添加web依赖(spring-boot-starter-web)。新建HelloController.java

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@CrossOrigin(origins="*")    //允许跨域请求
public class HelloController {
	
	@GetMapping("/resource")
	public Map<String,Object> home() {
		Map<String,Object> model = new HashMap<String,Object>();
		model.put("id", UUID.randomUUID().toString());
		model.put("content", "Hello World");
		return model;
	}	
}

运行Spring项目,在CMD中执行$ curl localhost:8080/resource

三. 在Vue项目中,使用 axios 访问 API

1. 安装axios和vue-axios(npm install --save-dev axios vue-axios)。

2. 修改src/main.js。

//main.js

import axios from axios
import VueAxios from vue-axios

Vue.use(VueAxios, axios);

3. 修改src/components/HelloWorld.vue,使用axios请求数据。

// components/HelloWorld.vue
  mounted(){
    this.axios.get(resource)
      .then(response => {
        console.log(response.data)
        this.greeting = response.data;
      })
      .catch(error => {
        console.log(error)
      })
  }

4. 修改config/index.js,设置代理服务器,解决跨域问题。

以上代理服务器内容只能在“开发模式”下才能使用。在生产模式下,只能靠服务器的nginx特性来解决js跨域问题。

5. 运行Vue项目

Spring项目和Vue项目都没有配置端口的话,先运行Spring项目,Spring项目将运行在8080端口。再运行Vue项目(npm run dev),Vue项目将运行在8081端口。

6. 浏览器中访问

参考:

经验分享 程序员 微信小程序 职场和发展