关于前端:Vue中vonlisteners和vbindprops的使用方法

2次阅读

共计 1478 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0