Reputation: 2997
In vue3, I try to add attributes like $attrsWithoutIdClassStyle
and $attrsIdClassStyleOnly
to the globalProperties
which the values are based on the $attrs
of current vue-component
It can be achieved by the global mixins
import _ from 'lodash';
import { createApp } from 'vue';
import App from '~/App.vue';
createApp(App)
mixin({
computed: {
$attrsWithoutIdClassStyle() {
return _.omit(this.$attrs, ['id', 'class', 'style']);
},
$attrsIdClassStyleOnly() {
return _.pick(this.$attrs, ['id', 'class', 'style']);
},
}
})
But since the mixin
is not recommended in vue3 any more, also the code is ugly.
So, how can I add the custom attributes to the global properties via app-config-globalproperties
which is a dynamic value based on the current vm?
Upvotes: 0
Views: 177
Reputation: 14649
As the documentation suggests, the proper Vue 3 replacement is to use a composable function and import where needed.
composables/myAttrs.js
import { useAttrs } from 'vue';
import _ from 'lodash';
export function useMyAttrs() {
const attrs = useAttrs();
const attrsWithoutIdClassStyle = _.omit(attrs, ['id', 'class', 'style']);
const attrsIdClassStyleOnly = _.pick(attrs, ['id', 'class', 'style']);
return {
attrsWithoutIdClassStyle,
attrsIdClassStyleOnly
};
}
in your components,
import { useMyAttrs } from '@/composables/myAttrs';
const { attrsWithoutIdClassStyle, attrsIdClassStyleOnly } = useMyAttrs();
Upvotes: 1