M. Falex
M. Falex

Reputation: 89

Vue.js - Uncaught TypeError: Cannot read property 'push' of undefined at <anonymous>:1:12

I get an error message:

Uncaught TypeError: Cannot read property 'push' of undefined at :1:12

After trying to push another item to list todos via console in Chrome:

app3.todos.push({ text: "New item" })

Below is my code:

HTML

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Web for Vue.Js</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        window.onload = function () {
            var app3 = new Vue({
                el:"#app3",
                data: {
                    todos:[
                        {text: "1"},
                        {text: "2"},
                        {text: "3"},
                        {text: "4"}
                    ]
                }
            });
        }
    </script>
</head>
<body>
    <div id="app3">
        <ol>
            <li v-for="todo in todos">
                {{ todo.text }}
            </li>
        </ol>
    </div>
</body>

</html>

Upvotes: 2

Views: 2156

Answers (1)

J. Uruba
J. Uruba

Reputation: 26

Move your code out of the event handler for the page load and all will be fine. Otherwise, you won't be able to access the variable instance through the console.

Budulinek told you yesterday already. :)

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Web for Vue.Js</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <div id="app3">
        <ol>
            <li v-for="todo in todos">
                {{ todo.text }}
            </li>
        </ol>
    </div>
    <script>
            var app3 = new Vue({
                el:"#app3",
                data: {
                    todos:[
                        {text: "1"},
                        {text: "2"},
                        {text: "3"},
                        {text: "4"}
                    ]
                }
            });
    </script>
</body>

</html>

Upvotes: 1

Related Questions