如何打印组件的Vue.js的ID

时间:2018-01-26 04:15:53

标签: javascript jquery vue.js vuejs2

官方文件有一个链接:

SQLite.Net-PCL

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



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 = ''
    }
  }
})
&#13;
<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>
&#13;
&#13;
&#13;

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

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

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

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

1 个答案:

答案 0 :(得分:0)

首先,您需要向id实际提供<li is="todo-item" ... >,而不是v-bind:id="todo.id"。您需要添加console.log(this.id)

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

$arr = array(
    array('id' => 2, 'score' => 4.6),
    array('id' => 5, 'score' => 1.7),
    array('id' => 6, 'score' => 3.7),
);

usort($arr, 'sort_by_score');

function sort_by_score($a, $b) {
    return $b['score'] > $a['score'] ? 1 : -1;
}

var_dump($arr);

P.S。不要使用jQuery!在Vue中使用jQuery是一种代码味道。 Here's a pretty informational rant by Gitlab on why that is (plus more).