简体   繁体   English

如何打印 Vue.js 的组件 ID

[英]how can i print the component's id of Vue.js

there are a link of official document :有官方文档的链接:

https://v2.vuejs.org/v2/guide/list.html#v-for-with-a-Component 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 .我尝试打印 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?但结果是一样的,在这里输入图像描述,我应该如何打印 todo.id?

Firstly, you need to actually provide the id to the <li is="todo-item" ... > s, which isn't being done.首先,您需要将id实际提供给<li is="todo-item" ... > s,这还没有完成。 You need to add v-bind:id="todo.id" .您需要添加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) .话虽如此,如果您尝试从任何Vue 实例生命周期钩子中打印它,那么它就像console.log(this.id)一样简单。 For example:例如:

Vue.component('todo-item', {
  ...
  mounted(){
    console.log(this.id)
  }
}

PS don't use jQuery! PS不要使用jQuery! Using jQuery with Vue is a code-smell.将 jQuery 与 Vue 一起使用是一种代码味道。 Here's a pretty informational rant by Gitlab on why that is (plus more). 这是 Gitlab 关于为什么会这样(以及更多)的信息性咆哮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM