zoukankan      html  css  js  c++  java
  • Vue组件传值(三)之 深层嵌套组件传值

    $attrs

        包含了父作用域中不作为 prop 被识别 (且获取) 的特性绑定 (class 和 style 除外)。当一个组件没有声明任何 prop 时,这里会包含所有父作用域的绑定 (class和 style 除外),并且可以通过 v-bind="$attrs" 传入内部组件——在创建高级别的组件时非常有用。

    $listener

        包含了父作用域中的 (不含 .native 修饰器的) v-on 事件监听器。它可以通过 v-on="$listeners" 传入内部组件——在创建更高层次的组件时非常有用。

        以上内容参考官网:https://cn.vuejs.org/v2/api/#vm-attrs

    直接看使用代码:

     1 在父组件当中,最外层组件
     2 
     3 <template>
     4     <div>
     5         <Child1 :child1Info="child1" :child2Info="child2" v-on:test1="onTest1" v-on:test2="onTest2">
     6         </Child1>
     7     </div>
     8 </template>
     9 <script>
    10 import Child1 from './child1';
    11 export default {
    12     data() {
    13         return {
    14             child1:"hahha",
    15             child2:"asdsdasd"
    16         };
    17     },
    18     components: { Child1 },
    19     methods: {
    20         onTest1(msg) {
    21             console.log('test1 running...',msg);
    22         },
    23         onTest2(msg) {
    24             console.log('test2 running',msg);
    25         }
    26     }
    27 };
    28 </script>
     1 //在子组件中
     2 
     3 <template>
     4     <div class="child-1">
     5         <p>在子组件当中:</p>
     6         <p>props-child1Info: {{child1Info}}</p>
     7         <p>$attrs: {{$attrs}}</p>
     8         <hr>
     9         <!-- Child2组件中能直接触发test的原因在于 B组件调用C组件时 使用 v-on 绑定了$listeners 属性 -->
    10         <!-- 通过v-bind 绑定$attrs属性,Child2组件可以直接获取到A组件中传递下来的props(除了child1组件中props声明的) -->
    11         <Child2 v-bind="$attrs" v-on="$listeners"></Child2>
    12     </div>
    13 </template>
    14 <script>
    15 import Child2 from './child2';
    16 export default {
    17     props: ['child1Info'],
    18     data() {
    19         return {};
    20     },
    21     components: { Child2 },
    22     mounted() {
    23         this.$emit('test1','嘻嘻');
    24     }
    25 };
    26 </script>
     1 //在孙子组件当中:
     2 
     3 
     4 <template>
     5     <div class="child-2">
     6         <p>在最里层组件当中child2:</p>
     7         <p>props-child2Info: {{child2Info}}</p>
     8         <p> $attrs 的值: {{$attrs}}</p>
     9         <hr>
    10     </div>
    11 </template>
    12 <script>
    13 export default {
    14     props: ['child2Info'],
    15     data() {
    16         return {};
    17     },
    18     mounted() {
    19         this.$emit('test2','哈哈');
    20     }
    21 };
    22 </script>
  • 相关阅读:
    uva 1510
    ADN中国团队參加微软的Kinect全国大赛获得三等奖
    在 window7 window8下公布webService注意问题
    html5调用手机摄像头,实现拍照上传功能
    4、深入理解Bean
    恶补jquery(四)jquery中事件--冒泡
    html5css3杂记
    Core Data 和 sqlite3的性能对比【图】3gs,iPhone4,4s,5的性能测试。
    boost 的函数式编程库 Phoenix入门学习
    information_schema模式表介绍 processlist
  • 原文地址:https://www.cnblogs.com/yuzhongyu/p/10490228.html
Copyright © 2011-2022 走看看