0

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();

1
  • 1
    use a mixin Commented Nov 26, 2022 at 16:46

1 Answer 1

1

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!

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

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.