Springboot + vue实现简单前后端分离

1.vue环境搭建与项目创建

vue2.0推荐开发环境

image.png

安装完node.js后打开cmd小黑窗安装淘宝镜像,用cnpm代替npm,依赖全速度快


npm install -g cnpm --registry=https://registry.npm.taobao.org

安装的WebPack

cnpm install webpack -g

安装VUE脚手架

npm install vue-cli -g

测试是否安装成功

image.png

在硬盘上找一个文件夹放工程用的,在终端中进入该目录

cd 目录路径

根据模板创建项目

vue init webpack vueDemo

image.png

安装项目依赖

cnpm install

创建完成后的样子

image.png

启动项目

cnpm run dev

帅气界面默认80端口没有去XXX链接

image.png


参考简书

2.vue设置路由

如果创建好的vue项目里没有vue-router路由依赖需要自行添加,我的创建项目时添加过了,所以省略

cnpm install vue-router --save

用Vue.js + vue-router创建单页应用,是非常简单的。使用Vue.js,我们已经可以通过组合组件来组成应用程序,当你要把vue-router添加进来,我们需要做的是,将组件(components)映射到路由(routes),然后告诉vue-router在哪里渲染它们

新创建vue项目时,会有设置好的主页面和vue组件,为了方便我直接在原有的上面修改
修改组件添加其他页面的路径App.vue修改后

<h1>Hello App!</h1>
              <p>
                <!-- 使用 router-link 组件来导航. -->
                <!-- 通过传入 `to` 属性指定链接. -->
                <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
                    <router-link to="/">Go to 首页</router-link>
                    <router-link to="/foo">Go to Foo</router-link>
                    <router-link to="/bar">Go to Bar</router-link>
              </p>
               <!-- 路由出口 -->
             <!-- 路由匹配到的组件将渲染在这里 -->
    <router-view/>

设置路由配置路径对应加载vue组件src / router / index.js修改后


import Vue from 'vue'
import Router from 'vue-router'
import HelloWorld from '@/components/HelloWorld'
import Foo from '@/components/Foo'
import Bar from '@/components/Bar'

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'HelloWorld',
      component: HelloWorld
    },
    {
      path: '/foo',
      name: 'Foo',
      component: Foo
    },
    {
      path: '/bar',
      name: 'Bar',
      component: Bar
    }
  ]
})

新建Foo.vue和Bar.vue为了在路由地址改变后加载后显示相应的元素

先不贴代码 后面会贴

vue渲染视图main.js修改后


import Vue from 'vue'
import App from './App'
//引入组件
import Foo from './components/Foo'
import Bar from './components/Bar'
import router from './router'
//引入resource
import VueResource from 'vue-resource'
//引入jQuery
import $ from 'jquery'
Vue.use(VueResource);

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  render: h => h(App)
})

参考VUE官网

3.vue与后台交互vue-resource jquery涉及到的问题跨域

如果没有资源和jquery依赖需先添加
资源

cnpm install vue-resource --save

jquery设置全局

cnpm install jquery --save

在build文件夹下的webpack.base.conf.js文件中添加:var webpack = require(“webpack”)


// 增加一个plugins
   plugins: [
      new webpack.optimize.CommonsChunkPlugin('common.js'),
      new webpack.ProvidePlugin({
          jQuery: "jquery",
          $: "jquery"
      })

   ],

跨域相关jsonp vue设置proxyTable
jsonp没有在本地测试用的豆瓣公共接口

前面提到的Foo.vue
<template>
    <div id="foo">
        foo
    <ul>
      <li v-for="article in articles">
        {{article.title}}
      </li>
    </ul>
    </div>
</template>

<script>
    export default {
  name: 'Foo',
  data () {
    return {
      articles: []
    }
  },
  mounted: function() {
    this.$http.jsonp('https://api.douban.com/v2/movie/top250?count=10', {}, {
        headers: {

        },
        emulateJSON: true
    }).then(function(response) {
      // 这里是处理正确的回调
        debugger
        this.articles = response.data.subjects
        // this.articles = response.data["subjects"] 也可以

    }, function(response) {
        // 这里是处理错误的回调
        console.log(response)
    });
  }

}
</script>

<style>
</style>

jsonp跨域参考
vue设置proxyTable config / index,js修改,前面提到的Bar.vue,SpringBoot控制器


proxyTable: {
             '/api': {
            target: 'http://localhost:8080',
                changeOrigin:true,
            pathRewrite: {
              '^/api': ''
            }
          }
    },
Bar.vue
通过ajax请求
            export default {
name: 'Bar',
data () {
    return {
      user: {}
    }
},
mounted: function() {
    var _self=this;
    $.ajax({
                url:"/api/article/get/"+"123",
//              url:"/api/courseOrder/search",
                type:"get",
                dataType: "JSON",
                async : false,
                success:function(result){
                    debugger
                        _self.user = result;
                },
                error:function(jqXHR, textStatus, errorThrown){
                    console.log("请求失败");
                    /*弹出jqXHR对象的信息*/
                    console.log(jqXHR.responseText);
                    console.log(jqXHR.status);
                    console.log(jqXHR.readyState);
                    console.log(jqXHR.statusText);
                    /*弹出其他两个参数的信息*/
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        }
}
通过 resource 请求
export default {
name: 'Bar',
data () {
    return {
      user: {}
    }
},
mounted: function() {
    this.$http.get('/api/article/get/'+'123', {}, {
//  this.$http.get('/api/courseOrder/search', {}, {
        headers: {

        },
//      emulateJSON: true
    }).then(function(response) {
      // 这里是处理正确的回调
        debugger
        this.user = response.data
        // this.articles = response.data["subjects"] 也可以

    }, function(response) {
        // 这里是处理错误的回调
        console.log(response)
    });
}

}
controller
package com.smallcode.springbootvuewsample.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
public class ArticleController {

    @GetMapping("/article/get/{id}")
    public Map get(@PathVariable int id) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("name", "test");
        map.put("desc", "testDesc");
        return map;
    }
}
    

vue修改端口号修改config / index.js port:8081


 // Various Dev Server settings
    host: 'localhost', // can be overwritten by process.env.HOST
    port: 8081, // 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-

springBoot项目生成



作者:不是一只咸鱼
链接:https://www.jianshu.com/p/915a80dcef80
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

猜你喜欢

转载自blog.csdn.net/qq_39530754/article/details/83016382