Complete vue to build the element-ui front-end project from scratch, and dock the back-end springboot project

1. Install the environment node

First of all: first download nodejs from nodejs.org and select the corresponding download.

Double-click to install, the installation interface has been Next

View the installed version number

Use Taobao NPM mirror

Everyone knows that it is very slow to directly use the official mirror of npm in China. Taobao NPM mirror is recommended here.

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

So you can use the npm command to install the module:

2. Install vue scaffolding

npm install vue-cli -g //Install vue-cli globally

After the installation is complete, check the version of vue

3. Create a vue project

vue create vue-ant demo (project name, arbitrary)

4. Use vscode to open the project, first npm install to install the dependencies, and then npm run serve to start the project

Last visit: http://localhost:8081/The    project was created successfully.

5. Introduce element-ui, npm i element-ui -S

6. Introduce element-ui in main.js

// 引入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 Just  find the corresponding component in the component library, and use the table component here.

<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. Start to view page effects

9. The data in the table here is fixed data. Then connect to the back end to obtain dynamic real data. First, integrate axios. npm i axios

9.1 http.js (same directory as main.js)


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

9.2 Introduce http.js in main.js

import http from './http.js'

Vue.prototype.$http = http

10. Leave the data in the table blank and connect to the backend to return the data

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


// 进入页面就加载数据

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

11.Springboot uses jpa to return simple data

Entity class

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

repository

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> {

}

controller

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

}

Database data

12. Start the front-end project to view the effect

So far, vue has used element-ui to connect to the back-end springboot to obtain data.

13. Axios uses post to submit data, the pit is a bit smaller 0.0

Define a method to save the user. The data defined here is fixed, so the page submission form is not used 0.0

Need to specify here

 headers: {
                'Content-Type': 'application/json; charset=UTF-8'
            },

默认是Content type 'application/x-www-form-urlencoded;charset=UTF-8' not supported.

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

Back-end interface, pay attention to using @RequestBody to receive the objects passed by the front-end

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

The same method is called in mounted to view the effect

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

Every time the page is refreshed, data will be added once, and the insertion is successful!

14.router route addition

npm install vue-router add dependency

Create router folder under 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
 

Introduce router in 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')

Modify app.vue to <router-view></router-view>

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

15. Create a new page Index

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

Click the button to jump to the userInfo page

16.Use the store module

npm install vuex

Create store folder, store.js and js on the opposite page of modules

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 injects the js of the above two modules

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 introduces 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')

Page index uses state

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

Check the effect of the page, and successfully use the state property stateA in index.js, the action is the same, and the user list js is the same.


Front-end project download

 

Guess you like

Origin blog.csdn.net/qq_33371766/article/details/110679423