Vue 3:从 attrs 中排除 fallthrough 属性
Vue 3: excluding fallthrough attributes from attrs
我正在开发一个自定义输入组件,它有一个父组件 div 和一个标签。我想将任何 classes 应用于父 div,但我还想确保任何其他 fallthrough 属性都应用于输入组件。
这是我的组件的简化版本
在App.vue
<script setup>
import { ref } from 'vue'
import MyInput from './MyInput.vue'
const msg = ref('I only want the outer blue box')
</script>
<template>
<h1>{{ msg }}</h1>
<my-input class="blue" aria-foo="foo" aria-bar="bar"/>
</template>
<style>
.blue {
padding: 1rem;
border: 3px solid blue;
}
</style>
在MyInput.vue
<template>
<div :class="attrs.class">
<input v-bind="attrs" >
</div>
</template>
<script>
export default {
inheritAttrs: false,
customOptions: {}
}
</script>
<script setup>
import { useAttrs, computed } from 'vue'
const attrs = useAttrs();
</script>
除了class,有什么好的方法可以得到所有attrs
吗?我尝试使用 computed
制作 attrs
的副本,但这似乎不起作用。
这是我试过的:
const inputAttrs = computed(()=>{
let returnObj = {}
for (attr in attrs) {
if (attr !== 'class') {
returnObj[attr] = attrs[attr]
}
}
return returnObj;
})
显然attr
在for循环中没有定义?本质上,我希望输入在没有 class
属性.
的情况下获得 aria-foo
和 aria-bar
属性
这是一个包含上述代码的 Link to the SFC Playground。
错误表明 attr 未定义,因为您需要使用 for...in[=18= 在 for() 中定义它]语法。
const inputAttrs = computed(()=>{
let returnObj = {}
// use const below
for (const attr in attrs) {
if (attr !== 'class') {
returnObj[attr] = attrs[attr]
}
}
return returnObj;
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
我正在开发一个自定义输入组件,它有一个父组件 div 和一个标签。我想将任何 classes 应用于父 div,但我还想确保任何其他 fallthrough 属性都应用于输入组件。
这是我的组件的简化版本
在App.vue
<script setup>
import { ref } from 'vue'
import MyInput from './MyInput.vue'
const msg = ref('I only want the outer blue box')
</script>
<template>
<h1>{{ msg }}</h1>
<my-input class="blue" aria-foo="foo" aria-bar="bar"/>
</template>
<style>
.blue {
padding: 1rem;
border: 3px solid blue;
}
</style>
在MyInput.vue
<template>
<div :class="attrs.class">
<input v-bind="attrs" >
</div>
</template>
<script>
export default {
inheritAttrs: false,
customOptions: {}
}
</script>
<script setup>
import { useAttrs, computed } from 'vue'
const attrs = useAttrs();
</script>
除了class,有什么好的方法可以得到所有attrs
吗?我尝试使用 computed
制作 attrs
的副本,但这似乎不起作用。
这是我试过的:
const inputAttrs = computed(()=>{
let returnObj = {}
for (attr in attrs) {
if (attr !== 'class') {
returnObj[attr] = attrs[attr]
}
}
return returnObj;
})
显然attr
在for循环中没有定义?本质上,我希望输入在没有 class
属性.
aria-foo
和 aria-bar
属性
这是一个包含上述代码的 Link to the SFC Playground。
错误表明 attr 未定义,因为您需要使用 for...in[=18= 在 for() 中定义它]语法。
const inputAttrs = computed(()=>{
let returnObj = {}
// use const below
for (const attr in attrs) {
if (attr !== 'class') {
returnObj[attr] = attrs[attr]
}
}
return returnObj;
})
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in