简体   繁体   中英

How to make a reusable vue js component?

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>

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.

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 .

You can use slot inside your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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