E
E
Emptyform2019-08-08 09:10:30
Vue.js
Emptyform, 2019-08-08 09:10:30

How to correctly intercept an event generated in a component?

Below is a completely simple, in my opinion, code, the meaning of which is that:
1. enter text into the input
2. click on the button
3. the `todo-add` component generates the `todoNew` event
4. the application (app) intercepts this event and calls the `addNewTodo` method which adds that value to the array.
Everything seems to be so, but the application does not see the event generated in the component, and a warning is displayed in the console:

`Event "todonew" is emitted in component but the handler is registered for "todoNew" ... You should probably use "todo-new" instead of "todoNew"`

Okay, change `todoNew` to `todo-new` and everything starts working.
What's the trouble? Why doesn't it work with `todoNew`?
<!doctype html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title></title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://unpkg.com/vue"></script>
</head>

<body>

<div id="app">
    <todo-add v-on:todoNew="addNewTodo"></todo-add>
    <p><pre>{{todosObj}}</pre></p>
</div>

<script>
    Vue.component('todo-add', {
        prps: ["name"],
        data: function() {
            return {
                name: ''
            }
        },
        template:
            `<ul>
                <input v-model="name" autofocus></input>
                <button v-on:click="add">Add New Todo</button>
            </ul>`,
        methods: {
            add: function() {
                this.$emit('todoNew', this.name);
            }
        }
    });

    var app = new Vue({
        el: "#app",
        data: {
            todoArr: [{id: 1, name: "aaaaaa"}]
        },
        methods: {
            addNewTodo: function(name) {
                let newItem = {id: this.todoArr.length+1, name: name}
                this.todoArr.push(newItem);
            }
        },
        computed: {
            todosObj: function() {
                return JSON.stringify(this.todoArr, null, 2 );
            }
        }
    });
</script>

</body>
</html>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
s_lukinin, 2019-08-08
@Emptyform

https://vuejs.org/v2/guide/components-props.html#P...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question