I have two Vue components with the same method (copy-paste). I would like to avoid that duplication and I am looking into the best way to do that. Note that the method uses mapped state and actions from Vuex.
I ended up creating a Renderless Component with the following outline:
<script>
import { mapState, mapActions } from 'vuex';
export default {
name: "CommonHandler",
render: () => null,
props: {
prop: {
type: User,
required: true,
},
},
methods: {
...mapActions({
mapAction1: "mappings/mapAction",
}),
commonMethod() {
/*Use computed variables and actions...*/
},
},
computed: {
...mapState({
users: state => state.users,
}),
currentUser() {
return this.users.find( element => element.id === this.prop.id );
},
},
};
</script>
Then, in those two components I instantiate the component above, add a ref to it, and just call the common method like this:
this.$refs.commonComponent.commonMethod();
Is this a good way to solve this problem?