Vue知识点—— $attrs

vue官网是这样介绍的:

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

<div id="app">
    A{{msg}}
    <my-button :msg="msg"></my-button>
  </div>

 

首先我们有三个组件A-B-C,然后想A中的属性传入C中,基本的做法是这样的,一层一层通过props往下传递
复制代码
  <script>
      let vm = new Vue({
        el: '#app',
        data: {
          msg: '100'
        },
        components: {
          'MyButton': {
            props: ['msg'],
            template: `<div>B<my-input :msg="msg"></my-input></div>`,
            components: {
              'MyInput': {
                props: ['msg'],
                template: '<div>C{{msg}}</div>'
              }
            }
          },
          
        }
      })
    </script>
复制代码
但是B中并没有使用到A中传递过来的属性,写props代码就是多余的了,那么$attrs可以接受上级传递过来的属性,那么我们就可以直接把$attrs传入下级
复制代码
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        msg: '100'
      },
      components: {
        'MyButton': {
          // props: ['msg'],
          template: `<div>B<my-input v-bind="$attrs"></my-input></div>`,
          components: {
            'MyInput': {
              props: ['msg'],
              template: '<div>C{{msg}}</div>'
            }
          }
        },
        
      }
    })
  </script>
复制代码

原文地址:https://www.cnblogs.com/wuxianqiang/p/10452662.html

posted @ 2020-10-16 10:01  月上弯  阅读(406)  评论(0编辑  收藏  举报