组件隔代通讯
v-on="$attrs"
主要用于组件之间的隔代传值。例如有 父组件A,子组件B,孙组件C 三个组件。 在A组件中传值给C,可直接在B中的C上设置v-bind="$attrs",然后在C组件中用prop接收,此时就直接把值传给了C。
用法如下:
组件A
<template>
<bCom msg='123'/>
</template>
组件B
<template>
<cCom v-bind="$attrs"/>
</template>
组件C
<template>
<div>A传递过来的值:{{msg}}</div>
</template>
<script>
export default {
name: 'cCom',
props: {
msg:{ //接收A传递的msg
typeof:String,
default:''
}
},
}
</script>
v-on="$listeners"用法
1种
用于底层组件向高级层组件传递信息。
例如有 父组件A,子组件B,孙组件C 三个组件,如果C传递信息给B则可直接使用$emit,如果是C向A传递信息还使用$emit,则就需要C先$emit给B,B再$emit给A,这种方式比较繁琐,则此时可以使用v-on="$listeners"来满足当前需求。
用例:
C组件
<template>
<div @click="onClick">C组件</div>
</template>
onClick(){
this.$emit("Msg",'123')
}
B组件
<template>
<cCom v-on="$listeners"/>
</template>
A组件
<template>
<bCom @Msg='Msg'/>
</template>
methods:{
Msg(val){
console.log(val) //123
}
}
2种
父组件调用子组件方法,给挂载子组件加方法,然后在子组件需要加的方法加v-on="$listeners",就可以访问到子组件,添加对应的方法
父组件
<template>
<Search @change="handleChangeClicks"></Search>
</template>
<script>
methods: {
handleChangeClicks(val) {
if (val.length) return;
this.getPurchaseOrderList();
},
}
</script>
子组件
v-on="$listeners"
<template>
<label class="input-search-label d-inline-flex align-items-center">
<i :class="`bx ${icon} label-icon`"></i>
<b-form-input
v-model="value"
v-on="$listeners"
type="search"
:placeholder="placeholder"
></b-form-input>
</label>
</template>
v-bind="$props"用法
组件A
<template>
<bCom :name="name" :age="age" />
</template>
data() {
return {
name: '传给父组件的值',
age: '18'
};
组件B
<template>
<div>组件名上绑定的非props特性($attrs): {{$attrs}}</div>
<cCom v-bind="$props"/>
</template>
props: ['name', 'age'],
组件C
<template>
<div>父组件传递过来的名称: {{name}}</div>
<div>父组件传递过来的年龄: {{age}}</div>
</template>
props: ['name', 'age'],
总的
index.vue页面
<template>
<div>
<h1>props、属性、事件传递</h1>
<app-parent test="123" :name="name" :age="age" v-on:start1="say1" @start2="say2"></app-parent>
</div>
</template>
<script>
import AppParent from './parent.vue';
export default {
data() {
return {
name: '传给父组件的值',
age: '18'
};
},
components: {
AppParent
},
methods: {
say1() {
console.log('第一个。。。。。');
},
say2() {
console.log('第二个。。。。。');
}
}
}
</script>
parent.vue组件
<template>
<div>
<h3>父组件</h3>
<div>组件名上绑定的非props特性($attrs): {{$attrs}}</div>
<app-child v-on="$listeners" v-bind="$props"></app-child>
</div>
</template>
<script>
import AppChild from './child.vue';
export default {
data() {
return {
};
},
inheritAttrs: false,
props: ['name', 'age'],
components: {
AppChild
},
mounted() {
this.$emit('start1');
}
}
</script>
child.vue组件
<template>
<div>
<h3>子组件</h3>
<div>父组件传递过来的名称: {{name}}</div>
<div>父组件传递过来的年龄: {{age}}</div>
</div>
</template>
<script>
export default {
data() {
return {
};
},
props: ['name', 'age'],
components: {},
created() {
},
mounted() {
this.$emit('start2');
},
}
</script>
图
转载
最后
感觉文章好的话记得点个心心和关注和收藏,有错的地方麻烦指正一下,如果需要转载,请标明出处,多谢!!!