javascript - 无法在 'Element' 上执行 'setAttribute':'0' 不是有效的属性名称
我创建了一个非常简单的 Vue 3 组件:
<template>
<input type="text" :value="value" >
</template>
<script lang="ts">
import { defineComponent } from 'vue'
export default defineComponent({
props:{
value: {type: String, default: ''}
}
});
</script>
使用下面的 HTML,我正在尝试在浏览器中渲染组件:
<div id="app">
{{message}}
<my-input></my-input>
</div>
这可以正常工作,但当我尝试将 value 属性传递给此组件时就会失败:
<my-input :value="message"></my-input>
这是错误,我在浏览器控制台中看到:
Uncaught DOMException: Failed to execute 'setAttribute' on 'Element': '0' is not a valid attribute name.
at patchAttr (https://unpkg.com/vue@next:9333:18)
at patchProp (https://unpkg.com/vue@next:9539:11)
at mountElement (https://unpkg.com/vue@next:6051:27)
at processElement (https://unpkg.com/vue@next:6024:15)
at patch (https://unpkg.com/vue@next:5944:23)
at ReactiveEffect.componentUpdateFn [as fn] (https://unpkg.com/vue@next:6484:23)
at ReactiveEffect.run (https://unpkg.com/vue@next:580:31)
at setupRenderEffect (https://unpkg.com/vue@next:6603:11)
at mountComponent (https://unpkg.com/vue@next:6386:11)
at processComponent (https://unpkg.com/vue@next:6344:19)
有什么说明为什么我会收到这个错误吗?谢谢你的帮助。
答案#1
我遇到了这个问题,但原因是另一个原因。我想从子组件向父组件传递属性和属性值,所以我在子组件上添加了 v-bind="[$attrs]",这 导致了错误
Parent.vue
<template>
<div>
{{ name }}
</div>
</template>
<script setup>
defineProps({
name: {
type: String
}
});
</script>
Child.vue
<template>
<Parent v-bind="[$attrs]" :class="{ 'active': modelValue }"/>
</template>
<script setup>
defineProps({
modelValue: {
type: Boolean,
default: false
}
})
</script>
然后我发现,当一个组件是另一个组件的根时,属性和特性会自动传递。
