加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vuejs之vue和springboot后端进行通信

发布时间:2020-12-16 23:03:59 所属栏目:百科 来源:网络整理
导读:一、新建一个vue项目,建立好后的相关文件 查看一下新建好的vue项目的结构: 当前各个文件中的内容: App.vue:主入口 template div id ="app" ="nav" router-link to ="/" Home / router-link | ="/about" About div router-view / style #app { font-famil

一、新建一个vue项目,建立好后的相关文件

查看一下新建好的vue项目的结构:

当前各个文件中的内容:

App.vue:主入口

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

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;
}
>

main.js:Vue.config.productionTip用于切换是生产环境还是开发环境。这里创建Vue对象的时候同时关联上了App.vue中的id名为app的div标签。引入路由router的js文件以及存储数据的store。

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中引入。

import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',name: 'Home''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 =  VueRouter({
  mode: 'history'default router

store/index.js

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default  Vuex.Store({
  state: {
  },mutations: {
  },actions: {
  },modules: {
  }
})

views/About.vue

class="about"h1>This is an about page>

views/Home.vue:这里面可以将component中的vue文件进行引入。

="home"img alt="Vue logo" src="../assets/logo.png"HelloWorld msg="Welcome to Your Vue.js App"script
// @ is an alias to /src
import HelloWorld from '@/components/HelloWorld.vue'

export default {
  name: 'Home',components: {
    HelloWorld
  }
}
>

当前效果是:

点击About:

就将内容切换到了About.vue。

二、自己定义页面并进行路由

在views下新建一个Test.vue

<!--只允许有一个根节点-->
  ="test"tabletr>
        td>编号>姓名>年龄>性别>邮箱>爱好>自我介绍tr v-for="(item,index) in users"
          :key="index">{{item.id}}>{{item.username}}>{{item.age}} >{{item.gender}}>{{item.email}}>{{item.hobby}}>{{item.introduce}}
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;
      })
  }
}
style scoped>

在router/index.js中

import Vue from 'vue'
import Home from '../views/Home.vue'
import Test from '../views/Test.vue' [
  {
    path: '/test',name: 'Test',component: Test,},
  {
    path: '/'default router

在App.vue中

 |
      <router-link to="/test">Test</router-link>
    >

三、新建一个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;

 javax.persistence.Entity;
 javax.persistence.Id;

@Entity
@Data
public  User {
    @Id
    private Integer id;
     String username;
     Integer age;
     Integer gender;
     String email;
     String hobby;
     String introduce;

}

Entity用于标识是一个实体类,Data用于自动生成getter和setter等方法,Id用于标识主键。

UserRepository.java

 com.gong.springbootvue.repository;

 com.gong.springbootvue.entity.User;
 org.springframework.data.jpa.repository.JpaRepository;

interface UserRepository  extends JpaRepository<User,Integer> {
}

继承了JpaRepository之后就会有相应的增删改查方法了,不需要自己写,第一个泛型是实体类类型,第二个泛型是主键类型。

UserController.java

 com.gong.springbootvue.controller;

 com.gong.springbootvue.repository.UserRepository;
 org.springframework.beans.factory.annotation.Autowired;
 org.springframework.stereotype.Controller;
 org.springframework.web.bind.annotation.RequestMapping;
 org.springframework.web.bind.annotation.ResponseBody;

 java.util.List;

@Controller
@RequestMapping("/user")
 UserController {

    @Autowired
    UserRepository userRepository;

    @ResponseBody
    @RequestMapping("/findAll")
    public List<User> getAll(){
        return userRepository.findAll();
    }

}

VueConfig.java

 com.gong.springbootvue.config;

 org.springframework.context.annotation.Configuration;
 org.springframework.web.servlet.config.annotation.CorsRegistry;
 org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
class VueConfig implements WebMvcConfigurer{
    @Override
    void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowedMethods("GET","HEAD","POST","PUT","DELETE","OPTIONS")
                .allowCredentials(true)
                .maxAge(3600)
                .allowedHeaders("*");
    }
}

四、分别启动后端服务和前端服务

先看下后端是否能正确运行:

再看下前端:

说明前端与后端交互成功。

总结:

后端中要配置与前端不同的端口,同时定义一个配置类用于配置与Vue进行交互。

前端使用axios发送请求获取后端传过来的json格式的数据,相关数据可以赋给data中的数据。使用created()方法在刷新页面时就发送请求。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读