标签:vue name default listeners attrs props 组件
简单来说:
$attrs
与$listeners
是两个「对象」,$attrs
里存放的是父组件中绑定的非 Props 属性,$listeners
里存放的是父组件中绑定的非原生事件。
//子组件
//$attrs 可以收集父组件中的所有传过来的属性 除了那些在组件中没有通过 props 定义的。
//唯一缺点 没在props定义的属性 会显示在生成的html标签上
//解决办法:通过inheritAttrs:false,避免顶层容器继承属性
<template>
<el-dialog
:title="title"
:visible="dialogVisible"
@close="$emit('update:dialogVisible', false)"
:width="width"
:close-on-click-modal="modal"
v-bind="$attrs" /**关键代码**
>
<slot name="dialog-body"></slot>
<div slot="footer" class="dialog-footer">
<slot name="modal-footer">
<el-button @click="$emit('update:dialogVisible', false)">取 消</el-button>
<el-button type="primary" @click="$emit('confirm')" size="small">确 定</el-button>
</slot>
</div>
</el-dialog>
</template>
<script>
export default {
name: "my-dialog",
inheritAttrs:false #关键代码
props: {
dialogVisible: Boolean,
title: String,
width: {
type: String,
default: "500px"
},
modal: {
type: Boolean,
default: false
}
}
};
</script>
//父组件 里使用
//:fullscreen="true" 并没在子组件props内定义 依然传入了子组件
//让dialog 全屏
<my-dialog :fullscreen="true" :dialogVisible.sync="flag" @confirm="close" title="测试弹框"></my-dialog>
其他例子
//componentA
<template>
<div class="component-a">
<component-b :name="name" :tag="tag" :age="age" @click.native="say" @mouseover="sing"></component-b>
</div>
</template>
<script>
import componentB from "./ComponentB";
export default {
name: "componentA",
components: { componentB },
data() {
return {
name: "六哥",
tag: "帅",
age: 18
};
},
methods: {
say() {},
sing() {}
}
};
</script>
//componentB
<template>
<div class="component-b" v-on="$listeners" v-bind="$attrs"></div>
</template>
<script>
export default {
name: "ComponentB",
props: {
age: Number
},
mounted() {
console.log(this.$attrs, this.$listeners);
//{name: "六哥", tag: "帅"}, {mouseover: ƒ}
}
};
</script>
标签:vue,name,default,listeners,attrs,props,组件 来源: https://www.cnblogs.com/cjh1996/p/12812652.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。