使用Spring Boot,Vue.js,Axios完成CRUD

在AQAP系列的最后一篇文章之后,下面是依赖于Spring(Boot),Vue.js和Axios的完整的create-read-update-delete(CRUD)应用程序。

实际观看:

我没有提到Thymeleaf,因为本文的后端所服务的页面没有变化。

我将使用Role实体来说明代码,但与往常一样,最后将提供完整的代码和正在运行的应用程序。

无需再费周折...

Adding REST operations

我们开始在上添加两个新操作RoleController.java:

@PostMapping("roles")
public Role save(@RequestBody Role role) {
    return roleRepository.save(role);
}

@DeleteMapping("roles/{id}")
public void get(@PathVariable Long id) {
    roleRepository.deleteById(id);
}

的保存方法兼顾了两者创建和更新 operations. Spring is smart enough to 更新 when there's an ID present和to 创建 a new entity otherwise.

The Role Form

现在是我们的HTML表单:

<form v-on:submit.prevent="postRole">
    <div class="card mb-auto">
        <div aria-controls="roleForm" aria-expanded="false" class="card-header" data-target="#roleForm"
             data-toggle="collapse" id="formHeader" style="cursor: pointer">
            <div class="float-left">New/Edit Role</div>
            <div class="float-right">+</div>
        </div>
        <div class="card card-body collapse" id="roleForm">
            <div class="form-group row">
                <label for="roleName" class="col-sm-4 col-form-label">Role Name</label>
                <input id="roleId" type="hidden" v-model="role_id">
                <input id="roleName" class="form-control col-sm-8" placeholder="Role Name" type="text"
                           v-model="role_name"/>
            </div>
            <div class="form-group row">
                <div class="col col-sm-4"></div>
                <input class="btn btn-primary col col-sm-8" type="submit" value="Save">
            </div>
        </div>
    </div>
</form>

这里有两件事要注意:

  • v-on:submit.prevent =“ postRole”是Vue.js标记,用于指定提交表单时要运行的方法,并防止在提交时重新加载页面的默认行为。模型是另一个Vue.js标记。 这会将输入与Vue.js数据绑定在一起。

New Edit and Delete buttons

在动作HTML表格的一列,只需添加两个新按钮:

<td>
    <button class="btn btn-primary" v-on:click="editRole(role)">Edit</button>
    <button class="btn btn-danger" v-on:click="deleteRole(role)">Delete</button>
</td>

注意相同上电标签,但现在具有点击. This binds the button 点击 to a Vue.js method.

The Vue.js Magic... again.

我们的Vue.js脚本现在有点吓人了:

<script>
    var app = new Vue({
        el: '#main',
        data() {
            return {
                roles: null,
                role_id: '',
                role_name: '',
            }
        },
        mounted(){
            this.getRoles();
        },
        methods: {
            getRoles: function () {
                axios
                    .get("/api/v1/roles")
                    .then(response => (this.roles = response.data))
            },
            postRole: function (event) {
                // Creating
                if (this.role_id == '' || this.role_id == null) {
                    axios
                        .post("/api/v1/roles", {
                            "name": this.role_name,
                        })
                        .then(savedRole => {
                            this.roles.push(savedRole.data);
                            this.role_name = '';
                            this.role_id = '';
                        })
                } else { // Updating
                    axios
                        .post("/api/v1/roles", {
                            "id": this.role_id,
                            "name": this.role_name,
                        })
                        .then(savedRole => {
                            this.getRoles();
                            this.role_name = '';
                            this.role_id = '';
                        })
                }
            },
            editRole: function (role) {
                this.role_id = role.id;
                this.role_name = role.name;
                document.getElementById('roleForm').setAttribute("class", document.getElementById('roleForm').getAttribute("class") + " show");
            },
            deleteRole: async function (role) {
                await axios
                    .delete("/api/v1/roles/" + role.id);
                this.getRoles();
            }
        },
    })
</script>

但这实际上很简单。 让我们探讨重要的事情:

  • 埃尔:“#main”指定Vue.js将对此HTML元素ID进行操作。 在我们的情况下,这是div包含表格和表格。内数据()我们可以指定将要在脚本上操作并且用户可以与之交互的变量。 在我们的案例中,请注意,我们已经定义了代表用户与之交互形式的内容的变量。已安装()在Vue.js准备就绪时调用(安装在埃尔以上)。 这里我们称一个方法getRoles()。 此方法向API请求数据并将其设置为用于创建目录的变量(使用v为在上一篇文章中进行了解释)。方法 contains all the 方法 that interact with the API. Notice how they equate to the CRUD operations:getRoles是个读操作。postRole是个创建操作。editRole是个更新操作。d埃尔eteRole是个d埃尔ete操作。

The app

You can see the app running here (slightly modified since this is an ongoing analysis).

The repository and the aforementioned commits, also slightly modified, here.

GitHub logo brunodrugowick / spring-thymeleaf-vue-crud-example

Complete CRUD example project with Spring Boot, Thymeleaf, Vue.js and Axios.

AQAP Series

尽可能快(AQAP)是我发现有趣的一系列快速文章。 我鼓励(并参与)有关注释的讨论,以进一步探索此处快速解释的技术,库或代码。


Image by Jason King por Pixabay

from: https://dev.to//brunodrugowick/complete-crud-with-spring-boot-vue-js-axios-fg1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值