简体   繁体   English

如何在 Vue 中创建动态编辑器表单组件

[英]How do I create a dynamic editor form component in Vue

I am new to Vue.js.我是 Vue.js 的新手。 I'm creating an app where I use Vuetify and nuxt and want to have a reusable editor modal.我正在创建一个使用 Vuetify 和 nuxt 的应用程序,并希望拥有一个可重用的编辑器模式。 So far I figured out that I can use v-dialog.到目前为止,我发现我可以使用 v-dialog。 I have a list of pets and I want an editor for that pet to pop up when clicking Edit action link on each row.我有一个宠物列表,我希望在每行上单击“编辑”操作链接时弹出该宠物的编辑器。 The editor should load the pet object from backend and present the editor form.编辑器应该从后端加载宠物对象并呈现编辑器表单。 When the Save button in the modal is clicked the pet should be saved and parent notified so it can update the list.单击模式中的“保存”按钮时,应保存宠物并通知父母,以便它可以更新列表。 I want to be able to add pets on another page (say on a Persons page I want to be able to select existing pets and also register a new pet) using the same editor.我希望能够使用相同的编辑器在另一个页面上添加宠物(比如在个人页面上,我希望能够选择现有宠物并注册新宠物)。

Is there a recommended way to construct a component that can be signaled to load pet with given id or open an empty form and also handle saving pets and signaling parent that pet has been updated or created?是否有推荐的方法来构造一个组件,该组件可以发出信号以加载具有给定 id 的宠物或打开一个空表单,还可以处理保存宠物并通知父级宠物已更新或创建?

Why not use props for input signal and emit event for output signal?为什么不对输入信号使用 props 并为输出信号使用发射事件?

In the below example, editor component is reactive to petId and you can close dialog by setting petId to null在下面的示例中,编辑器组件对petId具有反应性,您可以通过将petId设置为null来关闭对话框

In EditorDialog.vue :EditorDialog.vue

<template>
  <v-dialog :value="petId !== null">
    <!-- You editor -->
    <v-button @click="onSave">Save</v-button>
  </v-dialog>
</template>

<script>
export default {
  props: {
    petId: {
      type: String,
      default: '' // '' means create new pet
    }
  },
  watch: {
    petId: {
      immediate: true,
      handler(petId) {
        if (petId === null) return
        // fetch data or create empty data
      }
    }
  }
  methods: {
    onSave(): {
      const data = xx // your logic here
      this.$emit('save', data)
    }
  }
}
</script>

And in the parent:在父级中:

<EditorDialog pet-id="blah" @save="handler" />

You can set pet-id initial to null and the dialog will not be rendered as open on server side.您可以将pet-id initial 设置为null并且该对话框不会在服务器端呈现为打开状态。 Also, you can remove immediate: true if initial value is always null此外,如果初始值始终为null ,您可以删除immediate: true

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM