天天看點

vue--$index is not defined報錯

今天學習Vue中遇到了一個報錯資訊:$index is not defined,是我寫了個for循環在HTML中,然後是因為版本的問題

下面是解決方法:

原來的是 v-for="todo  in  todos"    

v-on:click="removeTodo($index)//這個僅僅适用于1.0版本-------------

這個在Vue1.0版本中式适用的可以直接使用$index,但是在2.0是不适合的

在Vue 2.0版本中擷取索引我們需要通過 v-for = "(person ,index)  in items ",  點選事件不能使用$index,應該使用 v-on:click="removeTodo(index)

<div class="app">

<input v-model="newTodo" v-on:keyup.enter="addTodo">

<ul>

<li v-for="(todo,index) in todos">

<span>{{todo.text}}</span>

<button v-on:click="removeTodo(index)">X</button>

</li>

</ul>

</div>
           
var exe = new Vue({
            el: ".app",
            data: {
                newTodo: '',
                todos: [
                    { text: 'learn' },
                    // {text:'vue'},
                    // {text:'buildlk'}
                ]
            },
            methods: {
               addTodo: function () {
                    var text = this.newTodo.trim();
                    if (text) {
                        this.todos.push({ text: text });
                        this.newTodo = '';
                    }
                },
                removeTodo: function (index) {
                    this.todos.splice(index, 1);
                }
            }
        });