【问题标题】:how can i print the component's id of Vue.js如何打印 Vue.js 的组件 ID
【发布时间】:2018-07-05 11:03:25
【问题描述】:

有官方文档的链接:

https://vuejs.org/v2/guide/list.html#v-for-with-a-Component

这是一个简单的待办事项列表的完整示例:

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>

结果: enter image description here


我尝试打印 todo.id 。例如:

Vue.component('todo-item', {
      template: '\
        <li>\
          {{ id }}-{{ title }}\
          <button v-on:click="$emit(\'remove\')">X</button>\
        </li>\
      ',
      props: ['id','title']
    })

但结果是一样的 enter image description here 那么,我应该如何打印 todo.id?

【问题讨论】:

标签: javascript jquery vue.js vuejs2


【解决方案1】:

首先,您需要将id 实际提供给&lt;li is="todo-item" ... &gt;s,这还没有完成。您需要添加v-bind:id="todo.id"

话虽如此,如果您尝试从the Vue instance lifecycle hooks 中的任何一个打印它,那么它就像console.log(this.id) 一样简单。例如:

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

附:不要使用 jQuery!将 jQuery 与 Vue 一起使用是一种代码味道。 Here's a pretty informational rant by Gitlab on why that is (plus more).

【讨论】:

    猜你喜欢
    • 2019-06-03
    • 1970-01-01
    • 2021-05-11
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-23
    • 2019-02-07
    相关资源
    最近更新 更多