非props的Attribute?inheritAttrs

  1. 非props的Attribute属性就是在子组件中没有使用props属性接收的属性,但在父元素中传递的属性
<template>
	<div id = "app">
		<h1>
			非props的Attribute?inheritAttrs
		</h1>
		<my-input></my-input>
	</div>
</template>
import MyInput from './components/MyInput.vue';

export default{
	components:{
		MyInput,
	}
}

直接在封装好的组件上添加属性,属性添加到组件的根元素上

	<my-input type="text"></my-input>
	<!-- MyInput组件将解析成如下所示 -->
	<template>
		<div type="text" class="input-container">
			<input />
		</div>
	</template>

设置inheritAttrs属性为false会阻止属性添加到根元素上这一属性

export default {
	name:'MyInput',
	inheritAttrs:false
}

在子组件中使用$attrs来接收父组件传递过来的属性

<template>
	<div class="input-container">
		<input v-bind="$attrs" />
	</div>
</template>
export default{
	inheritAttrs:false
}

完整示例

<template>
	<div id="app">
		    <div>
			  <h1>非props的Attribute?inheritAttrs</h1>
			  <my-input type="password" yan="YEN"></my-input>
			</div>
  	</div>
</template>
<template>
  <div class="input-container">
      <input type="text" v-bind="$attrs">
      {{$attrs}}
  </div>
</template>
export default {
  inheritAttrs: false
}

解析完成的文件

<div data-v-7ba5bd90="" class="input-container"><input type="text" yan="YEN"> 
	{"type": "password", "yan": "YEN"}
</div>
posted @ 2022-01-10 09:12  YAN-YAN  阅读(36)  评论(0)    收藏  举报