默认的属性传递给组件,会赋值在组件的根元素上
赋值在组件自定义标签上:
(1)组件的选项中设置 inheritAttrs: false
export default {
inheritAttrs:false,
}
(2)使用$attrs,在自定义标签上使用
<template>
<label>
<input
v-bind="$attrs"
>
</label>
</template>
代码示例:
效果图:
父元素:
new Vue({
el: '#app',
router,
data: {
name: {
required: true,
placeholder: 'Enter your username'
}
},
components: {
App },
template: '<App :name="name" />'
})
子元素:
<template>
<label>
<input
v-bind="$attrs"
v-on:input="$emit('input', $event.target.value)"
>
</label>
</template>
<script>
export default {
inheritAttrs:false,
name: 'App',
data(){
return{
}
},
methods:{
},
computed:{
},
watch:{
},
mounted(){
console.log(this.name)
console.log(this.$attrs);
}
}
</script>
<style>
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>