why attributes is Non-reactive object? #13989
Unanswered
tangjian1891
asked this question in
Help/Questions
Replies: 1 comment
-
|
Hello! This is an excellent question about Vue's reactivity system. The behavior you're observing is intentional and here's why: What "Stateful" Means vs "Reactive":
Why import { isReactive, watch } from 'vue';
console.log(isReactive(attrs));
watch(() => attrs.class, (newClass) => {
console.log('Class changed:', newClass);
});
watch(attrs, (newAttrs) => {
});The Design Rationale:
Proper Usage Patterns: <script setup>
import { useAttrs, watch } from 'vue';
const attrs = useAttrs();
watch(() => attrs.class, (newClass) => {
console.log('Class changed:', newClass);
});
const hasDataAttribute = computed(() => 'data-test' in attrs);
watch(attrs, () => {
});
watchEffect(() => {
console.log('Current class:', attrs.class);
console.log('Current style:', attrs.style);
});
</script>
<template>
<div v-bind="attrs">
{{ hasDataAttribute }}
</div>
</template>When You Need Full Reactivity: <script setup>
import { reactive, toRefs, watch } from 'vue';
const { class: className, style } = toRefs(useAttrs());
const reactiveAttrs = reactive({ ...useAttrs() });
watch(reactiveAttrs, (newAttrs) => {
});
</script>Key Takeaways:
This design strikes a balance between functionality and performance for the most common attribute use cases. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
i noticed that attrs is a proxy object.
docs https://vuejs.org/api/composition-api-setup.html#setup-context. "attrs and slots are stateful objects".
i don't know what is the difference between reactive object and stateful object.
i can't find them in the "Glossary"
#8421 Using
isReactive(attrs)returns false,but attrs in watch or computed is correct.i am very confused. why is it designed this way?
Beta Was this translation helpful? Give feedback.
All reactions