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"写在子组件中,就能够让孙子组件和父组件建立联系。