[Vuejs]-How to refactor for template variations & shared methods

2👍

I think v-bind is your friend here, and <component>, with a PostModel

Create a PostModel that predefines all the functions and properties of your re-usable post:

export default {
    post: {},
    canEditPost: function() {},
    targetPageUrl: '',
    //...
}

Then import your SinglePost (or whichever you need) along with the PostModel

import SinglePost from '/path/to/SinglePost';
import PostModel from './path/to/PostModel';

export default {

    data() {
        return {
            thePostComponent: SinglePost,
            postProps: Object.assign({}, PostModel, {
                post: post,
                canEditPost: canEditPost,
                targetPageUrl: targetPageUrl
            }
        }
    }
}

The idea above is that you’re overwriting the object with any custom configurations for a given post, but you don’t need to continuously define the properties on the component its self, creating a more self-contained and reusable component. If you’re passing these properties in from, say, an API, you could even more easily integrate this to make this more flat and reusable by using the Interceptor pattern to map your model to the API.

And finally, dynamically display that component:

For a reusable component:

<component :is="thePostComponent" v-bind="postProps">

Hopefully this helps

Leave a comment