0

I am new to Vue JS. I have created two different components Login and Register but with same form code I mean like email input and password input and a submit button, I got familiar with Mixins, so I created a mixin for submitting the form and I am using the same mixin in both register and login

// this is mixin

data() {
    return {
      email: "",
      password: ""
    };
  },

  methods: {
    onSubmit() {
      console.log(this.email);
    },
  },

How can I create a custom reusable component like this mixin , so I just want to pass props ? below is the login form and the register form is same like this I don't want to repeat

// this is Login Component

<v-form>

<v-text-field
type="email"
v-model="email"
label="E-Mail"></v-text-field>

<v-text-field
type="password"
v-model="password"
label="Password"></v-text-field>
<v-btn @click="onSubmit()" color="info">Submit</v-btn>

<script>
import CredMixin from "../mixins/Credentials";
export default {
  name: "Login",
  mixins: [CredMixin],
};
</script>

3 Answers 3

1

You can use slot inside your code.

Sign up to request clarification or add additional context in comments.

Comments

0

Vue makes it really simple to build reusable components.

You could create a component called form in components folder called customForm.vue

In that file you hold the everything thats required for the component in that file so its self contained.

<template> 
<v-form>

<v-text-field
type="email"
v-model="email"
label="E-Mail"></v-text-field>

<v-text-field
type="password"
v-model="password"
label="Password"></v-text-field>
<v-btn @click="onSubmit()" color="info">Submit</v-btn>
</template>
<script>
import CredMixin from "../path/to/your/mixin";
export default {
  name: "Login",
  mixins: [CredMixin],
};
</script>

Then in your layout or view you import the component.

import customForm from "@/components/customForm.vue"

Then you use it in your template like this;

<custom-form></custom-form>

You must also declare it as a component.

In your script for the layout or view.

components: {
   customForm, 
}

Then you can use that component in both layouts. Well in any layout like that so and so forth.

1 Comment

Also if you want to pass props you do that like so <custom-form :customProp= someProp > </custom-form>
0

This problem will be solved by adding template property to your mixin.

Do not add template section in the login and register component.

{
    template: `<v-form>

    <v-text-field
    type="email"
    v-model="email"
    label="E-Mail"></v-text-field>
    
    <v-text-field
    type="password"
    v-model="password"
    label="Password"></v-text-field>
    <v-btn @click="onSubmit()" color="info">Submit</v-btn>
    </v-form>
        `,

    data() {
       ...
      },
    
    methods: {
     ...
    },

}

Another solution is to use slot.

Comments

Your Answer

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