vue3:如何添加基于 $attr 的全局属性



在 vue3 中,我尝试将$attrsWithoutIdClassStyle$attrsIdClassStyleOnly等属性添加到值基于当前 vue-component$attrsglobalProperties

它可以通过全球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']);
},
}
})

但是由于 vue3 中不再推荐该mixin,因此代码也很丑陋。

那么,如何通过基于当前虚拟机的动态值app-config-globalproperties将自定义属性添加到全局属性中?

正如文档所建议的,正确的 Vue 3 替换是使用可组合函数并在需要时导入。

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
};
}

在您的组件中,

import { useMyAttrs } from '@/composables/myAttrs';
const { attrsWithoutIdClassStyle, attrsIdClassStyleOnly } = useMyAttrs();

最新更新