there are a link of official document :
https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Component
Here's a complete example of a simple todo list:
Vue.component('todo-item', { template: '\ <li>\ {{ title }}\ <button v-on:click="$emit(\'remove\')">X</button>\ </li>\ ', props: ['title'] }) new Vue({ el: '#todo-list-example', data: { newTodoText: '', todos: [ { id: 1, title: 'Do the dishes', }, { id: 2, title: 'Take out the trash', }, { id: 3, title: 'Mow the lawn' } ], nextTodoId: 4 }, methods: { addNewTodo: function () { this.todos.push({ id: this.nextTodoId++, title: this.newTodoText }) this.newTodoText = '' } } })
<div id="todo-list-example"> <input v-model="newTodoText" v-on:keyup.enter="addNewTodo" placeholder="Add a todo" > <ul> <li is="todo-item" v-for="(todo, index) in todos" v-bind:key="todo.id" v-bind:title="todo.title" v-on:remove="todos.splice(index, 1)" ></li> </ul> </div>
results: enter image description here
i try to print todo.id . for example:
Vue.component('todo-item', { template: '\ <li>\ {{ id }}-{{ title }}\ <button v-on:click="$emit(\'remove\')">X</button>\ </li>\ ', props: ['id','title'] })
but the result is the same enter image description here so, how should i print the todo.id?
Firstly, you need to actually provide the id
to the <li is="todo-item" ... >
s, which isn't being done. You need to add v-bind:id="todo.id"
.
That being said, if you're trying to print it from any of the Vue instance lifecycle hooks , then it's as easy as console.log(this.id)
. For example:
Vue.component('todo-item', {
...
mounted(){
console.log(this.id)
}
}
PS don't use jQuery! Using jQuery with Vue is a code-smell. Here's a pretty informational rant by Gitlab on why that is (plus more).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.