A
A
Artur Kudashev2020-01-09 19:35:48
Vue.js
Artur Kudashev, 2020-01-09 19:35:48

How to properly pass props to a component?

Hello, I myself develop on React, but I have to support projects on Vue. I can't quite figure out how to properly pass props to a component. There is an Input component :

<template>
    <input class="Input" v-bind="restProps" v-on="$listeners">
</template>

<script>
export default {
    props: ['placeholder', 'keyupEnter'],

    computed: {
        restProps: function() {
            return {  
                placeholder: this.placeholder
            }
        }
    }
}
</script>

<style lang="scss" scoped>
.Input {
    width: 100%;
    height: 42px;
    padding: 0 17px;
    font-size: 12px;
    border: 1px solid #E3E3E3;
    border-radius: 2px;
}
</style>

Here is how it is used:
<Input placeholder="Название вопроса"
       :value="question.name"
       @input="actions.changeQuestionName(index, $event)" />

<Input placeholder="Название ответа"
       @keyup.enter="actions.addQuestionAnswer.bind(null, index)" />

Problems:
  • As I understand it, there is no concept of restProps in Vue. You either need to throw all the props in a bunch through v-bind , or
    collect the necessary props into an object yourself to get something similar. Is this true or am I not understanding something?
  • The same can be done with handlers. You can throw a bunch through v-on , but for some reason
    @input works, and @keyup.enter does not want to work. What's the catch?

I read the docs, but I didn't really understand how to do it right. Maybe what I'm trying to do only works in React.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey delphinpro, 2020-01-09
@delphinpro

If I understand correctly, there are inheritAttrs and $attrs options .
And you can pass all properties
By default, undeclared props are hung on the root element of the component.
inheritAttrs can override this in order to put them on another element. for example

<div class="inputbox">
  <input v-bind="$attrs">
</div>
{
  inheritAttrs: false
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question