v-on="$listeners",用于底层组件调用高级层组件的方法。
v-bind="$props" 主要用于组件之间的隔代传值
下面通过一个demo来学习这两个功能,一共三个组件:父组件,子组件,孙子组件。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<div id="app">
<h3 @click="parentFun('父组件')">父组件</h3>
<child :fun="parentFun" v-on:parentfun='parentFun' v-bind:parentinfo="parentInfo"></child>
</div>
<script src="http://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
<script>
// 孙子组件-----------------------------------------------------------------------------------------------
Vue.component('grandchild', {
template:
`
<div @click="grandchildFun">
<h3>孙子组件</h3>
孙子组件{{parentinfo}}
</div>
`,
name: 'grandchild',
props: {
// 通过子组件中使用v-bind="$props",孙子组件可以获取父组件传递的参数
parentinfo: String
},
created() {
},
methods: {
grandchildFun() {
// 通过子组件中使用v-on="$listeners",孙子组件可以调用父组件的方法
this.$emit('parentfun', '孙子组件')
}
}
})
// 子组件-----------------------------------------------------------------------------------------------
Vue.component('child', {
template:
`
<div>
<h3 @click="useFun">子组件</h3>
<span>子组件{{parentinfo}}</span>
<grandchild v-on="$listeners" v-bind="$props"></grandchild>
</div>
`,
name: 'child',
props: {
// 子组件通过props获取父组件的方法
fun: Function,
parentinfo: String
},
created() {
},
methods: {
useFun() {
this.fun('子组件')
}
}
})
// 父组件-----------------------------------------------------------------------------------------------
new Vue({
name: 'parent',
el: '#app',
data() {
return {
parentInfo: '接收父组件里的数据'
}
},
methods: {
parentFun(argument) {
console.log(argument + '调用父组件的方法')
}
}
})
</script>
</body>
</html>
把v-on="$listeners"和v-bind="$props"写在子组件中,就可以让孙子组件和父组件建立联系。
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。