element-uiフロントエンドプロジェクトを最初からビルドし、バックエンドのスプリングブートプロジェクトをドッキングするための完全なvue

1.環境ノードをインストールします

まず、nodejs.orgからnodejsをダウンロードし、対応するダウンロードを選択します。

ダブルクリックしてインストールします。インストールインターフェイスは次のとおりです。

インストールされているバージョン番号を表示する

淘宝網NPMミラーを使用する

中国でnpmの公式ミラーを直接使用するのは非常に遅いことは誰もが知っています。ここでは淘宝網NPMミラーをお勧めします。

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

したがって、npmコマンドを使用してモジュールをインストールできます。

2.vueスキャフォールディングをインストールします

npm install vue-cli -g // vue-cliをグローバルにインストールします

インストールが完了したら、vueのバージョンを確認してください

3.vueプロジェクトを作成します

vue create vue-antデモ(プロジェクト名、任意)

4. vscodeを使用してプロジェクトを開き、最初にnpm installを使用して依存関係をインストールし、次にnpm runserveを使用してプロジェクトを開始します。

最終訪問:http:// localhost:8081 /   プロジェクトは正常に作成されました。

5. element-ui、npm i element-ui-Sを導入します

6.main.jsにelement-uiを導入します

// 引入element-ui

import ElementUI from 'element-ui'

import 'element-ui/lib/theme-chalk/index.css'

Vue.use(ElementUI)

7. https://element.eleme.cn/#/zh-CN/component/table コンポーネントライブラリで対応するコンポーネントを見つけて、ここでテーブルコンポーネントを使用します。

<template>
  <div>
    <h1>使用element-ui的表格</h1>
    <el-table
      :data="tableData"
      style="width: 100%">
      <el-table-column
        prop="date"
        label="日期"
        width="180">
      </el-table-column>
      <el-table-column
        prop="name"
        label="姓名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="address"
        label="地址">
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  props: {
    msg: String
  },
  data() {
      return {
        tableData: [{
          date: '2016-05-03',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-02',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-04',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-01',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-08',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-06',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }, {
          date: '2016-05-07',
          name: '王小虎',
          address: '上海市普陀区金沙江路 1518 弄'
        }],
        multipleSelection: []
      }
    },

    methods: {
      
    }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>

8.ページ効果の表示を開始します

9.ここの表のデータは固定データです。次に、バックエンドに接続して動的な実データを取得します。まず、axiosを統合します。npm i axios

9.1 http.js(main.jsと同じディレクトリ)


  import axios from 'axios'
  
  const http = axios.create({
    baseURL: "http://localhost:8080"
  })
  
  export  default http

9.2main.jsにhttp.jsを導入する

import http from './http.js'

Vue.prototype.$http = http

10.テーブルのデータを空白のままにし、バックエンドに接続してデータを返します

getUserInfo() {
        this.$http.get('/vue').then((result) => {
          console.log("获取的后端数据:", result);
          // 将获取的后端数据复制给表格的数据
          this.tableData = result.data;
        }).catch((err) => {
          console.log("获取的后端数据出错:", err);
        });


// 进入页面就加载数据

mounted() {
      this.getUserInfo();
    },

11.Springbootはjpaを使用して単純なデータを返します

エンティティクラス

package com.frank.jpaBatchSave.entity;

import lombok.Data;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import java.time.LocalDate;

/**
 * @author 小石潭记
 * @date 2020/12/5 17:52
 * @Description: ${todo}
 */
@Entity
@Data
public class VueUser {

    @Id
    @GeneratedValue
    private Long id;

    private String name;

    private String address;

    private LocalDate date;
}

リポジトリ

package com.frank.jpaBatchSave.repository;

import com.frank.jpaBatchSave.entity.User;
import com.frank.jpaBatchSave.entity.VueUser;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author 小石潭记
 */
@Repository
public interface VueUserRepository extends PagingAndSortingRepository<VueUser, Long> {

}

コントローラ

package com.frank.jpaBatchSave.web;

import com.frank.jpaBatchSave.entity.VueUser;
import com.frank.jpaBatchSave.repository.VueUserRepository;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.IteratorUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author 小石潭记
 * @date 2020/12/5 17:54
 * @Description: ${todo}
 */
@RestController
@RequestMapping("/vue")
@CrossOrigin
public class VueUserController {

    @Autowired
    private VueUserRepository repository;

    @GetMapping
    public List<VueUser> index() {
        Iterable<VueUser> all = repository.findAll();
        return Lists.newArrayList(all);
    }

}

データベースデータ

12.フロントエンドプロジェクトを開始して、効果を確認します

これまで、vueはelement-uiを使用してバックエンドのspringbootに接続し、データを取得してきました。

13. Axiosは投稿を使用してデータを送信しますが、ピットは少し小さくなっています0.0

ユーザーを保存する方法を定義します。ここで定義されたデータは固定されているため、ページ送信フォームは使用されません0.0

ここで指定する必要があります

 ヘッダー:{                 'Content-Type': 'application / json; charset = UTF-8 '             }、

默认是コンテンツタイプ 'application / x-www-form-urlencoded; charset = UTF-8'はサポートされていません。

saveUser() {
        let user = {
          name: '趵突泉',
          date: '2020-10-10',
          address: '山东省济南市趵突泉街101号'
        };
        
        this.$http({
            url: '/vue/save',
            method: 'POST',
            headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            },
            data: user
        }).then(res => {
            console.log("插入数据成功:", res);
            this.getUserInfo();
        }).catch(err => {
            console.log("插入数据失败:", err);
        })
      }

バックエンドインターフェイス。@ RequestBodyを使用してフロントエンドから渡されたオブジェクトを受信することに注意してください。

@PostMapping("/save")
    public String saveUser(@RequestBody VueUser user) {
        if (user.getName() != null) {
            repository.save(user);
            return "save success";
        }
        throw new MyException(USER_INFO_ERROR);
    }

効果を表示するために、同じメソッドがマウントで呼び出されます

 mounted() {
      this.getUserInfo();
      this.saveUser();
    },

ページが更新されるたびに、データが1回追加され、挿入が成功します。

14.ルータールートの追加

npm installvue-router依存関係を追加

src-> router.jsの下にルーターフォルダーを作成します

// 配置路由相关的信息
import VueRouter from 'vue-router'
import Vue from 'vue'
 
import Index from '../components/Index.vue'
import UserInfo from '../components/UserInfo.vue'
 
// 1.通过Vue.use(插件), 安装插件
Vue.use(VueRouter)
 
// 2.创建VueRouter对象
const routes = [
  {
    path: '',
    // redirect重定向
    redirect: '/index'
  },
  {
    path: '/index',
    component: Index
  },
  {
    path: '/user-info',
    component: UserInfo
  }
]
const router = new VueRouter({
  // 配置路由和组件之间的应用关系
  routes,
  mode: 'history',
  linkActiveClass: 'active'
})
 
// 3.将router对象传入到Vue实例
export default router
 

main.jsにルーターを導入

import Vue from 'vue'
import App from './App.vue'
// 引入element-ui
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
// 引入路由
import router from './router/router'

import http from './http.js'

Vue.prototype.$http = http

Vue.use(ElementUI)

Vue.config.productionTip = false

new Vue({
  // 引入路由
  router,
  render: h => h(App),
}).$mount('#app')

app.vueを<router-view> </ router-view>に変更します

<div id="app">
    <router-view></router-view>
  </div>

15.新しいページのインデックスを作成します

<template>
  <div>
    <h1>首页</h1>
    <el-button type="primary" @click="jumpUserInfo" style="margin-bottom: 25px">查看用户列表</el-button>
    <el-carousel indicator-position="outside">
      <el-carousel-item v-for="item in recordList" :key="item">
        <h3>{
   
   { item }}</h3>
      </el-carousel-item>
    </el-carousel>

    <el-carousel :interval="3000" type="card" height="200px">
      <el-carousel-item v-for="item in imagebox" :key="item.id">
        <img :src="item.idView" class="image">
        <span>{
   
   {item.text}}</span>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script>

export default {
  name: 'Index',
  props: {
    msg: String
  },
  data() {
      return {
        recordList: [
          '春', '夏', '秋', '冬'
        ],
        imagebox:[
          {
            id:1,
            text: '春天',
            idView:require('../assets/imagebox/1.jpg')
          },
          {
            id:2,
            text: '夏天',
            idView:require('../assets/imagebox/2.jpg')
          },
          {
            id:3,
            text: '秋天',
            idView:require('../assets/imagebox/3.jpg')
          },
          {
            id:4,
            text: '冬天',
            idView:require('../assets/imagebox/4.jpg')
          }
          //imagebox是assets下一个放图片的文件夹
        ]
      }
    },

    methods: {
     jumpUserInfo() {
       this.$router.push("/user-info");
     }
    },

    mounted() {
     
    },
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.el-carousel__item h3 {
    color: #475669;
    font-size: 18px;
    opacity: 0.75;
    line-height: 300px;
    margin: 0;
  }
  
  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }
  
  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }
</style>

ボタンをクリックして、userInfoページにジャンプします

16.ストアモジュールを使用する

npm install vuex

モジュールの反対側のページにストアフォルダー、store.js、jsを作成します

index.js

const state = {
    stateA: '首页的state'
  }
  
  const mutations = {
    showA (state) {
      return state.stateA
    }
  }
  
  const actions = {
    showAAction (context) {
      context.commit('showA')
    }
  }
  
  const getters = {
    getA (state) {
      return state.stateA
    }
  }
  export default {state, mutations, actions, getters}

user-info.js

const state = {
    stateB: '用户列表的state'
  }
  
  const mutations = {
    showB (state) {
      return state.stateB
    }
  }
  
  const actions = {
    showBAction (context) {
      context.commit('showB')
    }
  }
  
  const getters = {
    getB (state) {
      return state.stateB
    }
  }
  
  export default {state, mutations, actions, getters}

store.jsは、上記の2つのモジュールのjsを挿入します

import Vue from 'vue'
import Vuex from 'vuex'
import Index from './modules/index'
import UserInfo from './modules/user-info'

Vue.use(Vuex)

const store = new Vuex.Store({
    modules: {
        Index,
        UserInfo
    }
})

export default store

main.jsがstore.jsを紹介します

import Vue from 'vue'
import App from './App.vue'
// 引入element-ui
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import router from './router/router'
import store from './store/store'

import http from './http.js'

Vue.prototype.$http = http

Vue.use(ElementUI)

Vue.config.productionTip = false

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

ページインデックスは状態を使用します

import { mapState } from 'vuex'
computed: {
      ...mapState({
        index:  state => state.Index.stateA
      })
    }
 <h2>{
   
   {index}}</h2>

ページの効果を確認し、index.jsで状態属性stateAを正常に使用します。アクションは同じ方法で使用され、ユーザーリストのjsは同じ方法で使用されます。


フロントエンドプロジェクトのダウンロード

 

おすすめ

転載: blog.csdn.net/qq_33371766/article/details/110679423