vuejs之vue和springboot後端進行通訊

1、新建一個vue項目,創建好後的相關文件html

查看一下新建好的vue項目的結構:前端

當前各個文件中的內容:vue

App.vue:主入口java

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link>
    </div>
    <router-view/>
  </div>
</template>

<style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style>

main.js:Vue.config.productionTip用於切換是生產環境仍是開發環境。這裏建立Vue對象的時候同時關聯上了App.vue中的id名爲app的div標籤。引入路由router的js文件以及存儲數據的store。mysql

import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store' Vue.config.productionTip = false

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

router/index.js:這裏定義路由對應的模板。有兩種方式,一種是在開頭先引入,例如Home.vue。另外一種是先不引入,以後在component中引入。webpack

import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' Vue.use(VueRouter) const routes = [ { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router

store/index.jsios

import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ state: { }, mutations: { }, actions: { }, modules: { } })

views/About.vueweb

<template>
  <div class="about">
    <h1>This is an about page</h1>
  </div>
</template>

views/Home.vue:這裏面能夠將component中的vue文件進行引入。spring

<template>
  <div class="home">
    <img alt="Vue logo" src="../assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script> // @ is an alias to /src import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'Home', components: { HelloWorld } } </script>

當前效果是:vue-router

點擊About:

就將內容切換到了About.vue。

2、本身定義頁面並進行路由

在views下新建一個Test.vue

<template>
  <!--只容許有一個根節點-->
  <div class="test">
    <table>
      <tr>
        <td>編號</td>
        <td>姓名</td>
        <td>年齡</td>
        <td>性別</td>
        <td>郵箱</td>
        <td>愛好</td>
        <td>自我介紹</td>
      </tr>
      <tr v-for="(item, index) in users" :key="index">
        <td>{{item.id}}</td>
        <td>{{item.username}}</td>
        <td>{{item.age}} </td>
        <td>{{item.gender}}</td>
        <td>{{item.email}}</td>
        <td>{{item.hobby}}</td>
        <td>{{item.introduce}}</td>
      </tr>
    </table>
  </div>
</template>
<script> export default { name: "Book", data () { return { msg: "hello world", users: {}, } }, created () { const that = this; axios.get('http://localhost:8181/user/findAll/') .then(function (response) { console.log(response); that.users = response.data; }) } } </script>
<style scoped>
</style>

在router/index.js中

import Vue from 'vue' import VueRouter from 'vue-router' import Home from '../views/Home.vue' import Test from '../views/Test.vue' Vue.use(VueRouter) const routes = [  { path: '/test', name: 'Test', component: Test, }, { path: '/', name: 'Home', component: Home }, { path: '/about', name: 'About', // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue') } ] const router = new VueRouter({ mode: 'history', base: process.env.BASE_URL, routes }) export default router

在App.vue中

<template>
  <div id="app">
    <div id="nav">
      <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> | <router-link to="/test">Test</router-link>
    </div>
    <router-view/>
  </div>
</template>

<style> #app { font-family: Avenir, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; } #nav { padding: 30px; } #nav a { font-weight: bold; color: #2c3e50; } #nav a.router-link-exact-active { color: #42b983; } </style>

3、新建一個springboot項目,勾選上lombok、web、jpa、mysql

(1)配置鏈接數據庫以及jpa相關:後盾使用8181端口,前端使用8080端口。

spring: datasource: url: jdbc:mysql://localhost:3306/test username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver jpa: #控制檯顯示SQL show-sql: true properties: hibernate: format_sql: true server: port: 8181

(2)數據庫相關設計

(3) 新建一個entity包用於存放實體類、一個repository包用於存放jpa類,一個config包用於存放後端和前端跨域交互配置,一個controller。

User.java

package com.gong.springbootvue.entity; import lombok.Data; import javax.persistence.Entity; import javax.persistence.Id; @Entity @Data public class User { @Id private Integer id; private String username; private Integer age; private Integer gender; private String email; private String hobby; private String introduce; }

Entity用於標識是一個實體類,Data用於自動生成getter和setter等方法,Id用於標識主鍵。

UserRepository.java

package com.gong.springbootvue.repository; import com.gong.springbootvue.entity.User; import org.springframework.data.jpa.repository.JpaRepository; public interface UserRepository  extends JpaRepository<User,Integer> { }

繼承了JpaRepository以後就會有相應的增刪改查方法了,不須要本身寫,第一個泛型是實體類類型,第二個泛型是主鍵類型。

UserController.java

package com.gong.springbootvue.controller; import com.gong.springbootvue.entity.User; import com.gong.springbootvue.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller @RequestMapping("/user") public class UserController { @Autowired UserRepository userRepository; @ResponseBody @RequestMapping("/findAll") public List<User> getAll(){ return userRepository.findAll(); } }

VueConfig.java

package com.gong.springbootvue.config; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.CorsRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; @Configuration public class VueConfig implements WebMvcConfigurer{ @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("*") .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS") .allowCredentials(true) .maxAge(3600) .allowedHeaders("*"); } }

4、分別啓動後端服務和前端服務

先看下後端是否能正確運行:

再看下前端:

說明前端與後端交互成功。

總結:

後端中要配置與前端不一樣的端口,同時定義一個配置類用於配置與Vue進行交互。

前端使用axios發送請求獲取後端傳過來的json格式的數據,相關數據能夠賦給data中的數據。使用created()方法在刷新頁面時就發送請求。

原文出處:https://www.cnblogs.com/xiximayou/p/12336033.html

相關文章
相關標籤/搜索