3

Currently I have separate components CreateUser.vue and EditUser.vue with very big form.

  • Route for CreateUser is /users
  • Route for EditUser is /users/:username.

The backend API is also different:

  • POST for create (example.com/users) and
  • PUT for edit (example.com//users/:username).

Also in EditUser, username field is readonly as it cannot be edited once created otherwise both CreateUser and EditUser templates are same but Javascript part is different.

Question:

How can I combine this into one Component UserForm.vue and eliminate CreateUser.vue and EditUser.vue ?

In the main UI there is a button Create User which routes to CreateUser component. In the list of users view, each row has a button Edit which routes to EditUser component.

I am using Vue router for defining routes similar to below:

{
   path: '/users',
   name: 'createUser',
   component: CreateUser
},
{
   path: '/users/:id',
   component: EditUser,
   name: 'editUser'
}

2 Answers 2

5

You can pass parameters into your component via props property in router configuration and then use it as in answer above to render the necessary inputs...

{
  path: '/users',
  name: 'createUser',
  component: UserForm
  props: {editMode: false}
},
{
  path: '/users/:id',
  name: 'editUser'
  component: UserForm,
  props: {editMode: true}
}
Sign up to request clarification or add additional context in comments.

1 Comment

The how do you use '/users to load a list of users if it's mapped on createUser?
1

Just add a property on your UserForm.vue

props: {
    currentAction : {
        type : String,
        default: 'create',
        required: true
    },
},

you'll have to pass this string at

<user-form :currentAction="create"></user-form>

And in your component use it to call the necessary method createUser() or updateUser(). Also use it to render the necessary inputs and or calculate the necessary computed properties.

By what i see, this property will have to be a data property on your Main UI you'll have to change this property before you show the user-form.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.