简单聊聊vue2.x的$attrs和$listeners

简单聊聊vue2.x的$attrs和$listeners

目录

$attrs

$listeners

总结

$attrs

$attrs 用于多层次组件传递参数(组件标签的attribute,class和style除外),爷爷辈组件向孙子辈组件传递参数(注:参数不能被父辈prop识别,一旦被父辈prop识别且获取,则孙子辈组件不能获取到该参数)

写法如下:(注:v-bind不能用简写 :)

<grand-son v-bind="$attrs" />

下面举个栗子:

爷爷(GrandFather)向父亲(Father)传递一个 msg1

向孙子(GrandSon)传递一个 msg2,孙子会一并接收 msg1(然而被父亲接走了,所以孙子收不到 msg1)

<!-- GrandFather.vue --> <template> <div> GrandFather: <father :msg1="msg1" :msg2="msg2" /> </div> </template> <script> import Father from './Father.vue' export default { components: { Father }, data() { return { msg1: 'msg1', msg2: 'msg2' } } } </script> <!-- Father.vue --> <template> <div> Father: {{ msg1 }} <grand-son v-bind="$attrs" /> </div> </template> <script> import GrandSon from './GrandSon.vue' export default { components: { GrandSon }, props: ['msg1'] } </script> <!-- GrandSon.vue --> <template> <div>GrandSon: {{ msg1 }}{{ msg2 }}</div> </template> <script> export default { props: ['msg1', 'msg2'] } </script>

界面现实结果:

GrandFather:
Father: msg1
GrandSon: msg2

$listeners

$listeners 用于多层次组件传递事件监听器,爷爷辈组件向父辈、孙子辈、曾孙子辈……组件传递事件(与 $attrs 不同,不存在半路被拦截的情况)

写法如下:(注:v-on 不能用简写 @,虽然不报错,但是也不生效)

<grand-son v-on="$listeners" />

下面继续使用 爷爷-> 父亲 -> 孙子 的栗子:

爷爷(GrandFather)给父亲(Father)绑定一个 click 事件

父亲通过点击 div 触发 click 事件,同时向孙子(GrandSon)传递 $listeners

<!-- GrandFather.vue --> <template> <div> GrandFather: <father :msg1="msg1" :msg2="msg2" @click="handleClick" /> </div> </template> <script> import Father from './Father.vue' export default { components: { Father }, data() { return { msg1: 'msg1', msg2: 'msg2' } }, methods: { handleClick() { console.log('trriger click') } } } </script> <!-- Father.vue --> <template> <div> <div @click="handleFatherClick">Father: {{ msg1 }}</div> <grand-son v-bind="$attrs" v-on="$listeners" /> </div> </template> <script> import GrandSon from './GrandSon.vue' export default { components: { GrandSon }, props: ['msg1'], methods: { handleFatherClick() { console.log('father click') this.$emit('click') } } } </script> <!-- GrandSon.vue --> <template> <div @click="handleSonClick">GrandSon: {{ msg1 }}{{ msg2 }}</div> </template> <script> export default { props: ['msg1', 'msg2'], methods: { handleSonClick() { console.log('grandson click') this.$emit('click') } } } </script>

界面:

GrandFather:
Father: msg1
GrandSon: msg2

点击 Father: msg1,控制台显示:

father click
trriger click

点击 GrandSon: msg2,控制台显示:

grandson click
trriger click

总结

到此这篇关于vue2.x的$attrs和$listeners的文章就介绍到这了,更多相关vue2.x $attrs和$listeners内容请搜索易知道(ezd.cc)以前的文章或继续浏览下面的相关文章希望大家以后多多支持易知道(ezd.cc)!

推荐阅读