12 06 2023
可以使用路由参数来实现在同一个页面中进行新增和修改操作,并且能够读取和提交数据。 首先,在路由配置中定义一个动态路由参数,例如: ``` { path: '/edit/:id', name: 'edit', component: EditPage } ``` 其中,`:id` 表示动态路由参数,用于传递要编辑的数据的唯一标识。 然后,在组件中,可以通过 `$route.params.id` 来获取路由参数中的 `id` 值,进而根据该值从后端获取要编辑的数据。 在提交修改时,可以根据 `id` 值向后端发送修改请求,完成数据的更新。 完整的示例代码如下: ``` <template> <div> <h1>{{ title }}</h1> <form @submit.prevent="submitForm"> <label> Name: <input type="text" v-model="name"> </label> <label> Age: <input type="number" v-model="age"> </label> <button type="submit">{{ submitButtonText }}</button> </form> </div> </template> <script> export default { data() { return { id: null, name: '', age: '', title: '', submitButtonText: '' } }, created() { this.id = this.$route.params.id if (this.id) { // 根据 id 从后端获取要编辑的数据 // 然后将数据填充到表单中 this.title = 'Edit User' this.submitButtonText = 'Update' } else { this.title = 'Add User' this.submitButtonText = 'Create' } }, methods: { submitForm() { if (this.id) { // 根据 id 向后端发送修改请求 // 更新数据 } else { // 向后端发送新增请求 // 创建数据 } } } } </script> ```
延伸阅读
    党的二十大的大会主题内涵丰富,你如何理解?请根据中国近十年变化进行阐述,
    如何更好地协助公司进行创新和技术研发?
    植物通过什么进行光合作用?
    如何进行 Git 分支管理?
    如何进行后端消息推送和实时通信?