Web前端vue必做笔记之一:如何使用$attrs,inheritAttrs让你的组件可以更加灵活配置
组件MyInt.vue中
<template>
<div class="input-container">
<!-- $attrs保存了所有传过去的属性 -->
<input v-bind="$attrs" :value="value" @input="$emit('input')"/>
{{$attrs}}
</div>
</template>
<script>
export default {
props:['value'],
inheritAttrs:false //这个属性,可以禁止掉默认传过去属性会被添加到属性的根源上的行为
}
</script>
<style>
</style>
组件App.vue中
<template>
<div id="app">
<my-input v-model="message" type="text" placeholder="请输入用户名"></my-input>
<my-input v-model="message" type="password" placeholder="请输入密码"></my-input>
</div>
</template>
<script>
import MyInput from './components/MyInput'
export default {
components: {
MyInput
},
data() {
return {
message: 'hello world'
}
}
};
</script>
<style>
#app{
text-align: center;
}
</style>
本文详细介绍了Vue.js中组件如何利用$attrs和inheritAttrs属性进行更灵活的属性配置。通过在MyInt.vue组件中使用$vattrs绑定所有传入属性,并通过设置inheritAttrs为false阻止默认属性继承,实现自定义组件的输入框类型控制。在App.vue中,展示了如何通过v-model和不同type属性创建复用的my-input组件。

被折叠的 条评论
为什么被折叠?



