组件的数据传递
在封装组件时我们需要考虑到的一个问题是,如何对组件进行数据的传递。通常我们使用自定义属性 props 及自定义事件 emit。
定义一个输入框组件
<template>
<div class="container">
<input type="text" />
</div>
</template>
<script>
export default {
name: 'my-input',
}
</script>
在使用组件时,我们通过给组件添加属性的方式来传递数据
<my-input a="1" b="2" c="3"></my-input>
在组件中通过 props 定义属性名来接收传递过来的值并使用
<script>
export default {
name: 'my-input',
props: ['a', 'b', 'c']
}
</script>
什么是 $attrs
在组件中我们如果没有使用 props 来定义属性名的话,这些属性就会被继承到组件最外层的元素上,并放到 $attrs 中。
所以在实际开发过程中,我们一般是通过设置inheritAttrs 属性值为 false 来取消属性的继承,然后通过 v-bind='$attrs' 来使用这些未定义的属性。
<template>
<div class="container">
<input type="text" v-bind="$attrs" />
</div>
</template>
<script>
export default {
name: 'my-input',
inheritAttrs: false
}
</script>