0

我有默认的用户列表和按钮添加用户,它将用户添加到列表中。通过按下按钮创建的用户我想立即将用户添加到列表中标记为红色背景。让它即时使用

this.$watch("list", function() {

 this.$nextTick(function() {
   var index = this.list.length - 1;
   $(".wrapper .user:eq(" + index + ")").addClass('red');
 });

});

用户删除时它工作正常。当单击删除索引 var 时受影响的先前行。 https://jsfiddle.net/apokjqxx/37/ 如何重现:点击添加项目。然后删除创建的项目。托尼将有红色背景,但我只需要创建用户的红色背景。

如何获取已创建元素的 html 并仅在已创建元素 HTML 中使用 jquery?

4

1 回答 1

1

现在,对list变量的任何更改都会导致最后一项变为红色。您可以通过放置来解决问题

 this.$nextTick(function() {
   var index = this.list.length - 1;
   $(".wrapper .user:eq(" + index + ")").addClass('red');
 });

在你的addItems方法中。

但是,相反,我建议在您的列表中添加一个标志,以指示项目是否是新的。然后,使用该标志来确定该项目是否应为红色。

var listing = Vue.extend({
  template: '#users-template',
  data: function () {
    return {
      list: [],
    }
  },
  created: function() {
    this.loadItems();
  },
  methods: {
  	itemClass: function(item) {
    	return item.isNew ? 'red' : '';
    },
    loadItems: function() {
      this.list = [
      	{
          name: 'mike',
          isNew: false,
        },
        {
        	name: 'arnold',
          isNew: false,
        },
        {
        	name: 'tony',
          isNew: false
        }
      ];
    },
    addItems: function() {
      this.list.push({
      	name: 'Viktor',
        isNew: true
      });
    },
    removeItemUser: function (item) {
      this.list.splice(this.list.indexOf(item), 1)
    },
  }
});


Vue.component('listing', listing);
var app = new Vue({
  el: ".lists-wrappers",
});
.user{border: 1px solid; cursor: pointer}
.red{background-color:red}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.0-rc.3/vue.js"></script>
<div class="lists-wrappers">
  <listing></listing>
</div>
      
<template id="users-template">
  <div class="wrapper">
    <button @click="addItems()">Add item</button>
    <div  v-for="item in list"  :class="['user', itemClass(item)]">
      <div>{{item.name}}</div>
      <button class="destroy" @click="removeItemUser(item)">X</button>
    </div>
  </div>
</template> 

于 2016-11-24T23:31:36.080 回答