v-bind=“$attrs“ v-on=“$listeners“使用
使用场景:当vue中有多层组件嵌套, 且多层组件间需要相互传递数据时
A组件
<template>
<view class="bg-color-F4 reserve-box">
档期
<button @click="btnClick">
btn
</button>
<child v-bind.sync="obj" :a="'b'" @clickBtn="clickBtn"></child>
<midell-box :current-page="1"></midell-box>
</view>
</template>
<script>
import child from './components/child'
export default {
data() {
return {
obj:{
name:"old name",
title:"old title"
}
}
},
watch:{
obj:{
handler(newVal) {
console.log(newVal);
},
deep: true
}
},
created() {
},
methods: {
btnClick(){
uni.navigateTo({
url:`/pages/mealLabel/index`
})
},
clickBtn(){
console.log(1);
}
},
components: {
child
},
}
</script>
<style scoped lang="scss">
</style>
b组件
<!-- -->
<template>
<view>
<view @click="handleClick">{{title}}</view>
<view @click="changeName">{{name}}</view>
<bottom v-bind="$attrs" v-on="$listeners"></bottom>
</view>
</template>
<script>
import bottom from './bottom.vue'
export default {
props: {
title: String,
name: String
},
data() {
return {};
},
components: {bottom},
computed: {},
mounted() {
console.log('this.$attrs', this.$attrs)
},
methods: {
handleClick(e) {
this.$emit('update:title', 'new title')
// this.$emit('click', '新标题')
},
changeName() {
this.$emit('update:name', 'new name')
}
}
}
</script>
<style scoped lang="scss">
</style>
c组件
<!-- -->
<template>
<view>
<u-button type="primary" :text="a" @click="clickBtn"></u-button>
</view>
</template>
<script>
export default {
props: {
a: String,
name: String
},
data () {
return {
};
},
components: {},
computed: {},
mounted() {
console.log('this.$attrs', this.$attrs)
},
methods: {
clickBtn(){
this.$listeners.clickBtn()
}
}
}
</script>
<style scoped lang="scss">
</style>