vue $props, $attrs, $listeners

$props

官网内容

https://cn.vuejs.org/v2/api/#vm-props

vm.$props

2.2.0 新增

  • 类型:Object
  • 详细:

当前组件接收到的 props 对象。Vue 实例代理了对其 props 对象属性的访问。

$attrs属性

官网内容:

https://cn.vuejs.org/v2/api/#vm-attrs

2.4.0 新增

  • 类型:{ [key: string]: string }
  • 只读
  • 详细:

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

个人理解

$attrs即父元素绑定的属性中未在该组件的props中声明的属性值(除了class和style),可以通过这一属性在组件的目标元素中绑定这些属性。

$listeners

官网内容

vm.$listeners

2.4.0 新增

  • 类型:{ [key: string]: Function | Array<Function> }
  • 只读
  • 详细:

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

个人理解

可以通过$listeners获取父元素定义的事件,将对应事件绑定在子组件对应的元素上

综合举例

//父组件
<template>
  <div id="app">
    <div>
      <dailog-test/>
      <hello-world
        name='hah'
        age='12'
        father='tom'
        @focus="focusInput"
        @click="clickMe"
      >
        <div slot="footer" @click='slotClick'>hahhahahah</div>
      </hello-world>
    </div>
  </div>
</template>

<script>
import dailogTest from './components/dailogTest.vue'
import HelloWorld from './components/HelloWorld.vue'

export default {
  name: 'app',
  components: {
    dailogTest,
    HelloWorld
  },
  methods: {
    focusInput() {
      console.log('focus')
    },
    clickMe() {
      console.log('click')
    },
    slotClick() {
      console.log('slotClick')
    }
  }
}
</script>

// 子组件
<template>
  <div>
    genyuansu
    <div @click="header">hahahha</div>
    <!-- 在input上有父元素所有的事件 -->
    <input
      v-bind='{...$attrs, ...$props}'
      v-on="$listeners"
    >
    <!-- 在input上只有父元素点击事件 -->
    <input
      v-bind='{...$attrs, ...$props}'
      v-on="{click: $listeners.click}"
    >
    
    <slot name='footer' @click="footerC"></slot>
  </div>
</template>

<script>
export default {
  inheritAttrs: false,
  props: ['name', 'age'],
  data() {
    return {

    }
  },
  created() {

  },
  mounted() {
    this.$nextTick(() => {
      console.log(this.$props)
      console.log(this.$listeners)
      console.log(this.$attrs)
    })
  },
  methods: {
    header(){
      console.log('header')
    },
    // 无用,元素在哪里,在哪里声明方法,否则无用
    footerC() {

    }
  }
}
</script>

<style scoped>
input {
  margin-right: 20px;
}
</style>

在子元素中可以绑定上父元素传递过来的props和非props($attrs)属性

可看到打印出来的$props,$liseners,$attrs

分别点击1,2两个输入框的结果如上,1号输入框有父元素的focus和click事件,2号输入框有父元素的click事件

猜你喜欢

转载自blog.csdn.net/hulingyua/article/details/102746710
今日推荐