关于前端:Vue中vbindattrs的学习

3次阅读

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

我始终对 v -bind=“$attrs”和 v -bind=“$props”两个属性分不清楚,明天学习并总结了一下。

官网定义:

蕴含了父作用域中不作为 prop 被辨认 (且获取) 的 attribute 绑定 (class 和 style 除外)。当一个组件没有申明任何 prop 时,这里会蕴含所有父作用域的绑定 (class 和 style 除外),并且能够通过 v-bind=”$attrs” 传入外部组件——在创立高级别的组件时十分有用。

在网上看了前辈的解释:

当子组件没有申明或者说没有接管父组件传下来的 prop 属性时,那么父组件传下来的 prop 属性会被保留在子组件的 vm.$attrs 属性上。
这里指的父组件的意思是比拟宽泛的,是能够跨层级的父组件;如果子组件是下例的 grandson 组件,那么 father 组件和 son 组件均是它的父组件。

代码截图:

我在父组件中应用 v -bind 写了三个属性,在子组件中有一个 props1 是作为 props 接管的,其它两个没写在 props 外面阐明就是放在了 $attrs 属性上,在 created 外面打印 this.$attrs,失去 {attrs1: 1234567,attrs2: “ 接管父组件里的数据 ”}。

我一共写了三个组件:父组件,子组件,孙子组件。在子组件中写入 v -bind=”$attrs”,则孙子组件也能够接管父组件的子组件 attrs 属性了。
如果孙子组件须要同时接管 $attrs, $props,则在子组件写入 v -bind=”[$attrs, $props]” 即可。
上面是残缺的代码:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
</head>

<body>
  <div id="app">
    <h3> 父组件 </h3>
    <child v-bind:attrs2="attrs2" v-bind:attrs1="1234567" v-bind:props1="` 我是 props1`"></child>
  </div>
  <script src="http://cdn.bootcss.com/vue/2.5.16/vue.js"></script>
  <script>
    // 孙子组件 -----------------------------------------------------------------------------------------------
    Vue.component('grandchild', {
      template:
        `
        <div>
          <h3> 孙子组件 </h3>
          attrs 接管:{{$attrs.attrs1}}
          <br/>
          attrs 接管:{{$attrs.attrs2}}
          <br/>
          props 接管:{{props1}}
        </div>
        `,
      name: 'grandchild',
      inheritattrs: false,
      props: {props1: String},
      created() {console.log(this.$attrs, '$attrs')
      },
    })
    // 子组件 -----------------------------------------------------------------------------------------------
    Vue.component('child', {
      template:
        `
        <div>
          <h3> 子组件 </h3>
          attrs 接管:{{$attrs.attrs1}}
          <br/>
          attrs 接管:{{$attrs.attrs2}}
          <br/>
          props 接管:{{props1}}
          <grandchild v-on="$listeners" v-bind="[$attrs, $props]"></grandchild>
        </div>
        `,
      name: 'child',
      inheritattrs: false,
      props: {props1: String},
    })
    // 父组件 -----------------------------------------------------------------------------------------------
    new Vue({
      name: 'parent',
      // inheritattrs: false,
      el: '#app',
      data() {
        return {attrs2: '接管父组件里数据'}
      },
    })
  </script>
</body>

</html>
正文完
 0