vue工程搭建及调用后台spring boot工程

       前面笔者写过一片文章《一个Vue前端框架使用简单实例》,这种方案就是在html中直接使用script标签引入vue和一些常用的组件,这种方式和以前传统的开发是一样的,只是可以很爽的使用vue的双向数据绑定,这种方式只适合于普通的全栈开发,这不是我们推荐的方案。本篇使用一种新方案:即使用vue官方的脚手架创建单独的前端工程项目,做到和后端完全独立开发和部署,后端单独部署一个纯restful的服务。笔者使用最常用的用户登录用例来说明vue本篇所要叙述的内容。
一、实例环境
1)本次操作全在windows环境下
2)node.js已经安装,版本为v10.13.0
3)jdk已安装,版本为1.8
4)IntelliJ IDEA作为开发集成环境

二、后端工程
       本篇关注的是前端使用vue技术调用spring boot工程,spring boot工程一笔带过(如何创建spring boot工程请读者查找相关资料),spring boot工程为本地工程,端口为8090,所要调用的接口地址为/rest/login,
在这里插入图片描述在这里插入图片描述三、vue前端工程
       1.创建vue工程:
在idea中,依次file–》new–》project–》static web–》Vue.js,如下图
在这里插入图片描述点击next,输入login
在这里插入图片描述
一路点击next,知道最后生成一个vue工程login,如下图所示
在这里插入图片描述运行工程
在idea上运行Terminal,依次 view–》Tool windows–》Terminal,执行命令npm run dev,
在这里插入图片描述执行完后如下图:
在这里插入图片描述

在浏览器上运行http://localhost:8080,如下图
在这里插入图片描述
这时简单的demo就搭建完成了。

创建登录页面,并调用后端spring boot应用。
1)创建login页面,在目录/src/components创建登录页面login.vue。代码如下

<template>
  <Form ref="formInline" :model="formInline" :rules="ruleInline" inline>
    <FormItem prop="username">
      <Input type="text" v-model="formInline.username" placeholder="Username">
      <Icon type="ios-person-outline" slot="prepend"></Icon>
      </Input>
    </FormItem>
    <FormItem prop="password">
      <Input type="password" v-model="formInline.password" placeholder="Password">
      <Icon type="ios-lock-outline" slot="prepend"></Icon>
      </Input>
    </FormItem>
    <FormItem>
      <Button type="primary" @click="handleSubmit('formInline')">Signin</Button>
    </FormItem>
  </Form>

</template>
<script>
  export default {
    components: {
    },
    data () {
      return {
        formInline: {
          user: '',
          password: ''
        },
        ruleInline: {
          username: [
            { required: true, message: 'Please fill in the user name', trigger: 'blur' }
          ],
          password: [
            { required: true, message: 'Please fill in the password.', trigger: 'blur' },
            { type: 'string', min: 6, message: 'The password length cannot be less than 6 bits', trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      handleSubmit(name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.$axios({
              url: '/rest/login', //请求的地址
              method: 'post', //请求的方式
              data: this.formInline //请求的表单数据
            }).then(res => {
              console.info('后台返回的数据', res.data);
            }).catch(err => {
              console.info('报错的信息', err.response.message);
            });
          } else {
            this.$Message.error('表单校验失败!');
          }
        })
      }
    }
  }
</script>

将APP.vue中的代码换成,在script下代码添加import Login from ‘@/components/Login’
export default {
name: ‘App’,
components: {
‘Login’: Login
},代码如下:

<template>
  <div id="app">
    <router-view/>
    <!--<img src="./assets/logo.png">-->
  </div>
</template>
<script>
  import Login from '@/components/Login'
  export default {
    name: 'App',
    components: {
      'Login': Login
    },
    data() {
      return {}
    }
  }
</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;
  }
</style>

重新再启动,访问http://localhost:8080,展示如下界面:
在这里插入图片描述
Ok,登录界面改造完毕,下面来配置调用spring boot参数,打开/config/index.js,在module.exports= 的dev:{ 下添加

proxyTable: {
      '/rest': {
        target: 'http://localhost:8090',//设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,
        pathRewrite: {
          '^/rest': '/rest'
        }
      }
      },

其中http://localhost:8090为spring boot工程的开放地址和端口,host设置为localhost,代码如下:

'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.

const path = require('path')

module.exports = {
  dev: {

    // Paths
    assetsSubDirectory: 'static',
    assetsPublicPath: '/',
    proxyTable: {
      '/rest': {
        target: 'http://localhost:8090',//设置你调用的接口域名和端口号 别忘了加http
        changeOrigin: true,
        pathRewrite: {
          '^/rest': '/rest'
        }
      }
      },

    // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
    autoOpenBrowser: false,
    errorOverlay: true,
    notifyOnErrors: true,
    poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-

    // Use Eslint Loader?
    // If true, your code will be linted during bundling and
    // linting errors and warnings will be shown in the console.
    useEslint: true,
    // If true, eslint errors and warnings will also be shown in the error overlay
    // in the browser.
    showEslintErrorsInOverlay: false,

    /**
     * Source Maps
     */

    // https://webpack.js.org/configuration/devtool/#development
    devtool: 'cheap-module-eval-source-map',

    // If you have problems debugging vue-files in devtools,
    // set this to false - it *may* help
    // https://vue-loader.vuejs.org/en/options.html#cachebusting
    cacheBusting: true,

    cssSourceMap: true
  },

  build: {
    // Template for index.html
    index: path.resolve(__dirname, '../dist/index.html'),

    // Paths
    assetsRoot: path.resolve(__dirname, '../dist'),
    assetsSubDirectory: 'static',
    assetsPublicPath: './',

    /**
     * Source Maps
     */

    productionSourceMap: true,
    // https://webpack.js.org/configuration/devtool/#production
    devtool: '#source-map',

    // Gzip off by default as many popular static hosts such as
    // Surge or Netlify already gzip all static assets for you.
    // Before setting to `true`, make sure to:
    // npm install --save-dev compression-webpack-plugin
    productionGzip: false,
    productionGzipExtensions: ['js', 'css'],

    // Run the build command with an extra argument to
    // View the bundle analyzer report after build finishes:
    // `npm run build --report`
    // Set to `true` or `false` to always turn it on or off
    bundleAnalyzerReport: process.env.npm_config_report
  }
}

页面调用代码在login.vue已有叙述,不在累述。

测试
1)启动spring boot工程
2)重新启动login工程,进入login登录界面,输入用户名admin,密码123456,点击Signin,如下图
在这里插入图片描述3)查看spring boot工程console控制台输出,
在这里插入图片描述由此可见vue前端调用spring boot是成功的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值