easy-table-vue+VueJs、SpringBoot+Mybatis實現MVVM模型先後臺數據交互

該項目分爲前端展現部分後臺服務部分css

前端部分前端

  使用的技術是:NodeJs、Webpack、VueJsvue

  使用的組件庫是:IVIEW、easy-table-vuejava

  使用的開發工具是:WebStorm  連接:https://pan.baidu.com/s/1UBmLnRXM-IDcAiw72IESJw  提取碼:cuf0
node

  項目地址:https://gitee.com/wlovet/table-projectmysql

後臺部分webpack

  使用的技術是:Maven、SpringBoot、Mybatisios

  使用的開發工具是:IDeal  連接:https://pan.baidu.com/s/1wFeT50WYvNDNg6OQgs54qw  提取碼:64nr
git

  項目地址:https://gitee.com/wlovet/table-serverweb

交互的技術是 :axios

開發模式是:MVVM模式

該案例的目的是教你們從零搭建與編寫一個完整的而且能夠交互的項目!但願你們喜歡!

 

第一步:搭建前端服務器與環境

①安裝node.js,下載相應版本的node.js,下載地址:https://nodejs.org/en/download/,下載完雙擊安裝,點擊下一步直到安裝完成
②安裝完成後,附件裏選擇命令提示符(或者在開始的搜索框裏輸入cmd回車調出命令面板)輸入:node -v回車,出現相應版本證實安裝成功,  node環境已經安裝完成,因爲有些npm有些資源被屏蔽或者是國外資源的緣由,常常會致使用npm安裝依賴包的時候失敗,全部我還須要npm的  國內鏡像---cnpm。在命令行中輸入:npm install -g cnpm –registry=https://registry.npm.taobao.org回車,大約須要3分鐘,  若是報錯或沒反應,則卸掉node.js從新安裝 ③安裝全局vue-cli腳手架,用於幫助搭建所需的模板框架。輸入命令:cnpm install -g vue-cli回車等待完成。 ④建立項目,首先咱們要選定目錄,而後再命令行中把目錄轉到選定的目錄,假如咱們打算把項目新建在e盤下的vue文件夾中則輸入下面的命令:  e:回車,而後cd vue,而後輸入命令:vue init webpack 項目文件夾名稱,回車,運行初始化命令的時候會讓用戶輸入幾個基本的選項,  如項目名稱,描述,做者等信息,若是不想填直接回車默認就好。(一頓回車+N鍵就完成了)
⑤安裝項目所需的依賴包,首先輸入:cd 項目名回車,而後輸入:cnpm install回車等待安裝,安裝完成以後,會在咱們的項目目錄firstVue  文件夾中多出一個node_modules文件夾,這裏邊就是咱們項目須要的依賴包資源。安裝完依賴包以後,就能夠運行整個項目了。 ⑥測試環境是否搭建成功,在cmd裏輸入:cnpm run dev回車,項目運行成功後,瀏覽器會自動打開localhost:8080(若是瀏覽器沒有自動打開  ,能夠手動輸入)。運行成功後,會看到Welcome to Your Vue.js App頁面。

 

 

第二步:使用WebStorm打開easy-table-vue

結構圖以下:

一、引入IVIEW組件和easy-table-vue組件,在當前項目的cmd窗口輸入

cnpm install iview --save-dev

cnpm install vue-easytable --save-dev

二、打開main.js文件,使用這些組件

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//引入IVIEW組件
import iView from 'iview';
import 'iview/dist/styles/iview.css';
Vue.use(iView);
//引入vue-easytable
import 'vue-easytable/libs/themes-base/index.css'
import {VTable,VPagination} from 'vue-easytable'
Vue.component(VTable.name, VTable)
Vue.component(VPagination.name, VPagination)

Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

三、在src/components文件夾下新建文件TableMain.vue文件,添加代碼以下:

<template>
  <div class="layout">
    <Layout>
      <Header>
        <Menu mode="horizontal" theme="dark" active-name="1">
          <div class="layout-logo">IVIEW佈局</div>
          <div class="layout-nav">
            <MenuItem name="1">
              <Icon type="ios-navigate"></Icon>
              Item 1
            </MenuItem>
            <MenuItem name="2">
              <Icon type="ios-keypad"></Icon>
              Item 2
            </MenuItem>
            <MenuItem name="3">
              <Icon type="ios-analytics"></Icon>
              Item 3
            </MenuItem>
            <MenuItem name="4">
              <Icon type="ios-paper"></Icon>
              Item 4
            </MenuItem>
          </div>
        </Menu>
      </Header>
      <Content :style="{padding: '0 50px'}">
        <Breadcrumb :style="{margin: '20px 0'}">
          <BreadcrumbItem>Home</BreadcrumbItem>
          <BreadcrumbItem>Components</BreadcrumbItem>
          <BreadcrumbItem>Layout</BreadcrumbItem>
        </Breadcrumb>
        <Card>
          <div style="min-height: 200px;">
            <v-table
              is-horizontal-resize
              style="width:100%"
              :columns="columns"
              :table-data="tableData"
              row-hover-color="#eee"
              row-click-color="#edf7ff"
            ></v-table>
          </div>
        </Card>
      </Content>
      <Footer class="layout-footer-center"> &copy; 做者:不若爲止</Footer>
    </Layout>
  </div>
</template>

<script>
  export default {
    name: "table-main",
    data() {
      return {
        tableData: [
          {"name":"趙偉","tel":"156*****1987","hobby":"鋼琴、書法、唱歌","address":"上海市黃浦區金陵東路569號17樓"},
          {"name":"李偉","tel":"182*****1538","hobby":"鋼琴、書法、唱歌","address":"上海市奉賢區南橋鎮立新路12號2樓"},
          {"name":"孫偉","tel":"161*****0097","hobby":"鋼琴、書法、唱歌","address":"上海市崇明縣城橋鎮八一路739號"},
          {"name":"周偉","tel":"197*****1123","hobby":"鋼琴、書法、唱歌","address":"上海市青浦區青浦鎮章浜路24號"},
          {"name":"吳偉","tel":"183*****6678","hobby":"鋼琴、書法、唱歌","address":"上海市松江區樂都西路867-871號"},
          {"name":"趙偉","tel":"156*****1987","hobby":"鋼琴、書法、唱歌","address":"上海市黃浦區金陵東路569號17樓"},
          {"name":"李偉","tel":"182*****1538","hobby":"鋼琴、書法、唱歌","address":"上海市奉賢區南橋鎮立新路12號2樓"},
          {"name":"孫偉","tel":"161*****0097","hobby":"鋼琴、書法、唱歌","address":"上海市崇明縣城橋鎮八一路739號"},
          {"name":"周偉","tel":"197*****1123","hobby":"鋼琴、書法、唱歌","address":"上海市青浦區青浦鎮章浜路24號"},
          {"name":"吳偉","tel":"183*****6678","hobby":"鋼琴、書法、唱歌","address":"上海市松江區樂都西路867-871號"}
        ],
        columns: [
          {field: 'name', title: '姓名', width: 80, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'tel', title: '手機號碼', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'hobby', title: '愛好', width: 150, titleAlign: 'center', columnAlign: 'center',isResize:true},
          {field: 'address', title: '地址', width: 280, titleAlign: 'center', columnAlign: 'left',isResize:true}
        ]
      }
    }
  }
</script>

<style scoped>
  .layout{
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    height: 100%;
  }
  .layout-logo{
    width: 100px;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    float: left;
    position: relative;
    top: 15px;
    left: 20px;
    font-weight: bold;
    text-align: center;
    color: #49ffcc;
  }
  .layout-nav{
    width: 420px;
    margin: 0 auto;
    margin-right: 20px;
  }
  .layout-footer-center{
    text-align: center;
  }
</style>

四、修改src/router文件夾下的index.js,代碼以下:

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

Vue.use(Router)

export default new Router({
  routes: [
    {
      path: '/',
      name: 'Table',
      component: TableMain
    }
  ]
})

此時頁面展現以下:

如今界面的數據都是定死的,還不能作到與後臺交互。

 

第三步:執行下面的SQL腳本,將數據導入數據庫

CREATE TABLE persons 
(id  integer, 
create_datetime datetime, 
email varchar(255), 
phone varchar(255), 
sex varchar(255), 
username varchar(255), 
zone blob, 
primary key (id));
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'gubaoer@hotmail.com', 08613000001111, 'male', 'gubaoer', 'HongKou District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'boyle.gu@hotmail.com', 08613000001112, 'male', 'baoer.gu', 'JingAn District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'yoyo.wu@gmail.com', 08613000001113, 'female', 'yoyo.wu', 'JingAn District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'stacy.gao@126.com', 08613000001114, 'female', 'stacy.gao', 'MinHang District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'yomiko.zhu@qq.com', 08613000001115, 'female', 'yomiko.zhu', 'PuDong District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'hong.zhu@163.com', 08613000001116, 'male', 'hong.zhu', 'YangPu District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'leon.lai@qq.com', 08613000001117, 'male', 'leon.lai', 'JinShan District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'mark.lei@sohu.com', 08613000001118, 'male', 'mark.lei', 'HuangPu District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'wen.liu@360.com', 08613000001119, 'male', 'wen.liu', 'ChongMing District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'cai.lu@baidu.com', 08613000001120, 'female', 'cai.lu', 'BaoShan District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'alex.li@icee.com', 08613000001121, 'male', 'alex.li', 'ChangNing District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'sofia.xu@qq.com', 08613000001122, 'female', 'sofia.xu', 'ZhaBei District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'cora.zhang@qq.com', 08613000001123, 'female', 'cora.zhang', 'XuHui District');
INSERT INTO persons (create_datetime, email, phone, sex, username, zone) VALUES (now(), 'tom.gao@hotmail.com', 08613000001124, 'female', 'tom.gao', 'HuangPu District');

 

第四步:使用IDeal建立一個SpringBoot項目

此處教你們一個快速建立SpringBoot項目的辦法,這樣能夠省去編寫pom.xml的步驟,記得連上網絡

一、點擊New Project,選擇Spring Initializr,點擊

二、輸入包名和項目名,點擊next

三、這裏的操做就是在pom.xml配置你所須要的環境,配置好以後,點擊next,而後Finnish就建立好了一個項目啦

使用Eclipse或者MyEclipse的小夥伴,能夠建立一個Maven項目,把個人pom.xml文件的內容複製一下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.5.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.wzhi</groupId>
    <artifactId>tableserver</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>tableserver</name>
    <description>實現數據表格的先後臺交互</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.0.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

 

第五步:編寫後臺交互的業務代碼

完整的項目結構圖以下:

一、修改application.yml,添加配置內容以下:

mybatis:
    config-location: classpath:mybatis/mybatis.cfg.xml
    mapper-locations: classpath:mybatis/mapper/*.xml
    type-aliases-package: com.wzhi.tableserver.pojo
server:
    port: 8888
spring:
    application:
        name: table-server
    datasource:
        driver-class-name: com.mysql.cj.jdbc.Driver
        password: 123456
        url: jdbc:mysql://XXX.XXX.XXX.XXX:3306/test?characterEncoding=utf8&useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
        username: root

二、修改TableserverApplication.java,代碼以下:

/**
 * @author 不若爲止
 * @version 1.0
 * @class PersonService
 * @package com.wzhi.tableserver
 * @desc
 *           @MapperScan 的做用是掃描到文件夾下的@Mapper註解
 *           @Slf4j 是日誌打印註解
 *           @SpringBootApplication SpringBoot的啓動註解
 * @copyright weizhi
 * @date 2018/09/04
 */
@SpringBootApplication
@MapperScan(basePackages = "com.wzhi.tableserver.dao")
@Slf4j
public class TableserverApplication {
    public static void main(String[] args) {
        ConfigurableApplicationContext context =SpringApplication.run(TableserverApplication.class, args);
        log.info("該服務的名稱是:{}",context.getEnvironment().getProperty("spring.application.name"));
        log.info("該服務的啓動端口是:{}",context.getEnvironment().getProperty("server.port"));
    }
}

三、在config目錄下新建CorsConfig.java,解決axios的跨域問題,代碼以下:

package com.wzhi.tableserver.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
/**
 * @author 不若爲止
 * @version 1.0
 * @class CorsConfig
 * @package com.wzhi.tableserver.config
 * @desc 由於Vue使用的是axios進行後臺交互,因此須要配置一個過濾
 * @copyright weizhi
 * @date 2018/09/04
 */
@Configuration
public class CorsConfig {
    private CorsConfiguration buildConfig(){
        CorsConfiguration corsConfiguration =new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*");
        corsConfiguration.addAllowedHeader("*");
        corsConfiguration.addAllowedMethod("*");
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter(){
        //System.out.println("進入跨域處理");
        UrlBasedCorsConfigurationSource source=new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**",buildConfig());
        return new CorsFilter(source);
    }
}

四、新建Person.java實體類,代碼以下:

package com.wzhi.tableserver.pojo;

import lombok.Data;
import lombok.experimental.Accessors;

/**
 * @author 不若爲止
 * @version 1.0
 * @class Person
 * @package com.wzhi.tableserver.pojo
 * @desc 我的信息實體類
 * @copyright weizhi
 * @date 2018/09/04
 */
@Data
@Accessors(chain = true)
public class Person {
    private Integer id;
    private String userName;
    private String zone;
    private String email;
    private String sex;
    private String phone;
    private String createTime;
}

五、新建PersonMapper.java文件,代碼以下:

package com.wzhi.tableserver.dao;

import com.wzhi.tableserver.pojo.Person;
import org.apache.ibatis.annotations.Mapper;

import java.util.List;

/**
 * @author 不若爲止
 * @version 1.0
 * @class PersonMapper
 * @package com.wzhi.tableserver.dao
 * @desc 我的信息Mapper,此處的Mapper註解會被啓動類的@MapperScan掃描到
 * @copyright weizhi
 * @date 2018/09/04
 */
@Mapper
public interface PersonMapper {
    /**
     * @desc 查詢全部的用戶
     * @return
     */
    List<Person> findAll();
}

六、新建mybatis.cfg.xml和PersonMapping.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!-- 全局參數 -->
<configuration>
    <settings>
        <!-- 使全局的映射器啓用或禁用緩存。 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 全局啓用或禁用延遲加載。當禁用時,全部關聯對象都會即時加載。 -->
        <setting name="lazyLoadingEnabled" value="true" />
        <!-- 當啓用時,有延遲加載屬性的對象在被調用時將會徹底加載任意屬性。不然,每種屬性將會按須要加載。 -->
        <setting name="aggressiveLazyLoading" value="true" />
        <!-- 是否容許單條sql 返回多個數據集 (取決於驅動的兼容性) default:true -->
        <setting name="multipleResultSetsEnabled" value="true" />
        <!-- 是否可使用列的別名 (取決於驅動的兼容性) default:true -->
        <setting name="useColumnLabel" value="true" />
        <!-- 容許JDBC 生成主鍵。須要驅動器支持。若是設爲了true,這個設置將強制使用被生成的主鍵,有一些驅動器不兼容不過仍然能夠執行。 default:false -->
        <setting name="useGeneratedKeys" value="true" />
        <!-- 指定 MyBatis 如何自動映射 數據基表的列 NONE:不隱射 PARTIAL:部分 FULL:所有 -->
        <setting name="autoMappingBehavior" value="PARTIAL" />
        <!-- 這是默認的執行類型 (SIMPLE: 簡單; REUSE: 執行器可能重複使用prepared statements語句;BATCH: 
            執行器能夠重複執行語句和批量更新) -->
        <setting name="defaultExecutorType" value="SIMPLE" />
        <!-- 使用駝峯命名法轉換字段。 -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
        <!-- 設置本地緩存範圍 session:就會有數據的共享 statement:語句範圍 (這樣就不會有數據的共享 ) defalut:session -->
        <setting name="localCacheScope" value="SESSION" />
        <!-- 設置但JDBC類型爲空時,某些驅動程序 要指定值,default:OTHER,插入空值時不須要指定類型 -->
        <setting name="jdbcTypeForNull" value="NULL" />
    </settings>
</configuration>
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org/DTD Mapper 3.0" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.wzhi.tableserver.dao.PersonMapper">
    <resultMap type="com.wzhi.tableserver.pojo.Person" id="person">
        <result column="id" jdbcType="INTEGER" property="id"/>
        <result column="create_datetime" jdbcType="VARCHAR" property="createTime"/>
        <result column="email" jdbcType="VARCHAR" property="email"/>
        <result column="phone" jdbcType="VARCHAR" property="phone"/>
        <result column="sex" jdbcType="VARCHAR" property="sex"/>
        <result column="username" jdbcType="INTEGER" property="username"/>
        <result column="zone" jdbcType="VARCHAR" property="zone"/>
    </resultMap>
    <sql id="personColnum">
       id,create_datetime,email,phone,sex,username,zone
    </sql>
    <select id="findAll" resultMap="person">
        SELECT <include refid="personColnum"/>
        FROM persons
    </select>
</mapper>

七、新建PersonService.java和PersonServiceImpl.java

package com.wzhi.tableserver.service;

import com.wzhi.tableserver.pojo.Person;
import java.util.List;
/**
 * @author 不若爲止
 * @version 1.0
 * @class PersonService
 * @package com.wzhi.tableserver.service
 * @desc 我的信息Service
 * @copyright weizhi
 * @date 2018/09/04
 */
public interface PersonService {
    /**
     * @desc 查詢全部的用戶
     * @return
     */
    List<Person> findAll();
}
package com.wzhi.tableserver.service.impl;

import com.wzhi.tableserver.dao.PersonMapper;
import com.wzhi.tableserver.pojo.Person;
import com.wzhi.tableserver.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Slf4j
@Service
public class PersonServiceImpl implements PersonService {
    @Autowired
    private PersonMapper mapper;
    @Override
    public List<Person> findAll() {
        return mapper.findAll();
    }
}

八、新建PersonController.java,代碼以下:

package com.wzhi.tableserver.controller;

import com.wzhi.tableserver.pojo.Person;
import com.wzhi.tableserver.service.PersonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 不若爲止
 * @version 1.0
 * @class PersonController
 * @package com.wzhi.tableserver.controller
 * @desc 我的信息交互
 * @copyright weizhi
 * @date 2018/09/04
 */
@RestController
@Slf4j
public class PersonController {
    @Autowired
    private PersonService service;

    @GetMapping(value = "findAll")
    public List<Person> findAll(){
        log.info("查詢全部的角色信息");
        return service.findAll();
    }
}

 

第六步:實現先後臺的數據交互

一、在前端項目中引入axios,執行命令cnpm install axios --save-dev,修改在main.js爲:

// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//引入IVIEW組件
import iView from 'iview';
import 'iview/dist/styles/iview.css';
Vue.use(iView);
//引入vue-easytable
import 'vue-easytable/libs/themes-base/index.css'
import {VTable,VPagination} from 'vue-easytable'
Vue.component(VTable.name, VTable)
Vue.component(VPagination.name, VPagination)
//引入axios
import axios from 'axios' Vue.prototype.$ajax = axios Vue.config.productionTip = false

/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  components: { App },
  template: '<App/>'
})

二、修改TableMain.vue文件,修改數據從後臺服務獲取,代碼以下:

<template>
  <div class="layout">
    <Layout>
      <Header>
        <Menu mode="horizontal" theme="dark" active-name="1">
          <div class="layout-logo">IVIEW佈局</div>
          <div class="layout-nav">
            <MenuItem name="1">
              <Icon type="ios-navigate"></Icon>
              Item 1
            </MenuItem>
            <MenuItem name="2">
              <Icon type="ios-keypad"></Icon>
              Item 2
            </MenuItem>
            <MenuItem name="3">
              <Icon type="ios-analytics"></Icon>
              Item 3
            </MenuItem>
            <MenuItem name="4">
              <Icon type="ios-paper"></Icon>
              Item 4
            </MenuItem>
          </div>
        </Menu>
      </Header>
      <Content :style="{padding: '0 50px'}">
        <Breadcrumb :style="{margin: '20px 0'}">
          <BreadcrumbItem>Home</BreadcrumbItem>
          <BreadcrumbItem>Components</BreadcrumbItem>
          <BreadcrumbItem>Layout</BreadcrumbItem>
        </Breadcrumb>
        <Card>
          <div style="min-height: 200px;">
            <v-table
              is-horizontal-resize
              style="width:100%"
              :columns="columns"
              :table-data="tableData"
              row-hover-color="#eee"
              row-click-color="#edf7ff"
            ></v-table>
          </div>
        </Card>
      </Content>
      <Footer class="layout-footer-center"> &copy; 做者:不若爲止</Footer>
    </Layout>
  </div>
</template>

<script>
  export default {
    name: "table-main",
    data() {
      return {
        tableData: [],
        columns: [
          {field: 'userName', title: '姓名', width: 80, titleAlign: 'center', columnAlign: 'center', isResize: true},
          {field: 'phone', title: '手機號碼', width: 150, titleAlign: 'center', columnAlign: 'center', isResize: true},
          {field: 'sex', title: '性別', width: 150, titleAlign: 'center', columnAlign: 'center', isResize: true},
          {field: 'email', title: '電子郵箱', width: 280, titleAlign: 'center', columnAlign: 'left', isResize: true},
          {field: 'createTime', title: 'createTime', width: 150, titleAlign: 'center', columnAlign: 'center', isResize: true},
          {field: 'zone', title: 'zone', width: 150, titleAlign: 'center', columnAlign: 'center', isResize: true},
        ]
      }
    },
  created() { //在created函數中使用axios的get請求向後臺獲取用戶信息數據
      this.$ajax('http://localhost:8888/findAll').then(res => { this.tableData = res.data }).catch(function (error) { console.log(error); }); }

  }
</script>

<style scoped>
  .layout {
    border: 1px solid #d7dde4;
    background: #f5f7f9;
    position: relative;
    border-radius: 4px;
    overflow: hidden;
    height: 100%;
  }

  .layout-logo {
    width: 100px;
    height: 30px;
    background: #5b6270;
    border-radius: 3px;
    float: left;
    position: relative;
    top: 15px;
    left: 20px;
    font-weight: bold;
    text-align: center;
    color: #49ffcc;
  }

  .layout-nav {
    width: 420px;
    margin: 0 auto;
    margin-right: 20px;
  }

  .layout-footer-center {
    text-align: center;
  }
</style>

三、啓動TableServerApplication,刷新界面,從後臺查詢到數據以下:

編輯過程當中會遇的問題

一、使用WebStorm打開Vue項目沒有這樣的圖表

解決辦法:點擊File->Settings->Plugins,搜索Vue,下載點擊Apply重啓便可

二、有不少人會遇到CORS跨域請求的問題,一種解決辦法是在後臺編寫配置類MyCorsConfig.java

@Configuration
public class MyCorsConfig {    
    @Bean
    public WebMvcConfigurer corsConfigurer(){
     return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                // 限制了路徑和域名的訪問
                /*registry.addMapping("/api*").allowedOrigins("http://localhost:8081");*/
              registry.addMapping("/**")
                .allowedOrigins(ALL)
                .allowedMethods(ALL)
                .allowedHeaders(ALL)
                .allowCredentials(true);
            }
        };
    }        
}

也能夠在某個接口加上@CrossOrigin(origins = 「http://ip:port」)註解

相關文章
相關標籤/搜索