How to understand the $listeners attribute in vue? The example of the official website is not very clear, ask for advice?

1. The official website begins with an example of listening for a native event on the root element of a component using the .native modifier of v-on, for example,
< base-input Vmuri onconcentration focus.native = "onFocus" > < / base-input >
2. But if the < base-input > is refactored inside, the root element is actually a < label > element,

<label>
  {{ label }}
  <input
    v-bind="$attrs"
    v-bind:value="value"
    v-on:input="$emit("input", $event.target.value)"
  >
</label>

then the parent"s .native listener will fail, so vue provides the $listeners attribute
3. The next example is not very clear, as follows:

Vue.component("base-input", {
  inheritAttrs: false,
  props: ["label", "value"],
  computed: {
    inputListeners: function () {
      var vm = this
      // `Object.assign` 
      return Object.assign({},
        // 
        this.$listeners,
        // 
        // 
        {
          //  `v-model` 
          input: function (event) {
            vm.$emit("input", event.target.value)
          }
        }
      )
    }
  },
  template: `
    <label>
      {{ label }}
      <input
        v-bind="$attrs"
        v-bind:value="value"
        v-on="inputListeners"
      >
    </label>
  `
})
In the words of the

official website, the < base-input > component is now a completely transparent wrapper, which means it can be used exactly like a normal < input > element: all the same features and listeners work.
4. This example is very clear, but I don"t know what it means. Ask the boss to explain.

Mar.23,2022

first of all, what is $listeners ?

assume a parent component Parent and a child component Child

// Parent
<template>
  ...
  <child v-on:event-one="methodOne" v-on:event-two="methodTwo" />
  ...
</template>

then when you use Child , all incoming v-on events can be found in the $listeners object.

// Child
created () {
  console.log(this.$listeners) // { 'event-one': f(), 'event-two': f() }
}

so the computed-> inputListeners in the official example collects the v-on method passed in by the user when using the base-input component.
is then forwarded to the input box in the form of vmuron = "inputListeners" .
( vmuronn = "{a: f ()}" is equivalent to vriponlange a = "f ()" )

that's why the official website says that base-input is a transparent wrapper, because it really just forwards the parameters passed by the parent component to the input element.

Menu