Home > Back-end >  vuejs2 components code refactoring to avoid repeating element
vuejs2 components code refactoring to avoid repeating element

Time:11-28

below code is use in two components which are different.so Please don't say use props.. only use data variables & mostly methods are same(identical) but components templates are different.

<template>
   
</template>

<script>
export default {
    name: "abc",
    data() {
        return {
            address: {
                billing: {
                    address1: [],
                    first_name: "",
                    last_name: "",
                    email: "",
                    phone: "",
                    city: "",
                    postcode: ""
                },
            },
        };
    },
    created() {
    },
    mounted() {
    },
    updated() {
    },
    methods: {
        xyz() {},
    },
};
</script>

Which is best way to do?.. In vueJs3 Composite APi setup() hook best way to this..

but i'm using vuejs 2.my question is how to do this in vuejs2 so i can avoid repeating declare data variables & method

One Way to do is using service class(JavaScript Class) .

Service Name : utils.js

e.g this.utils.address.billing.address1 , this.utils.xyz(); but i want only access as in normal this.address.billing.address1; this.xyz();

CodePudding user response:

You should use a MIXIN like this:

Create file /src/mixins/SomeMixin.js

export default {
data() {
        return {
            address: {
                billing: {
                    address1: [],
                    first_name: "",
                    last_name: "",
                    email: "",
                    phone: "",
                    city: "",
                    postcode: ""
                },
            },
        };
    },
    created() {
    },
    mounted() {
    },
    updated() {
    },
    methods: {
        xyz() {},
    },
}

In Component do:

<script>
import AddresMixin from "./src/mixins/SomeMixin.js";
export default {
  name: "abc"
  mixins: [SomeMixin],
}
</script>

Component now have access to all data, computed and function defined in the mixin!

  • Related