繁体   English   中英

如何使用Ractive对数组中的新DOM条目进行样式设置?

[英]How do I style new DOM entries in an array using ractive?

我有一个修改阵列的Ractive实例。 当新值出现在数组中时,我想突出显示相应的元素。 目前,我是通过对新创建的元素进行一些样式设计来实现的。 这是一个jsfiddle

var ractive = new Ractive({
  el: 'main',
  template: `
    <h1>Hello {{name}}!</h1>

    {{ #things:index }}
      <p>{{ things[index] }}</p>  
    {{ /things }}

  `,
  data: function(){
    return {
      things: [
        'banana',
        'carrot'
      ]
    }
  },
  oncomplete: function(){
    var component = this;

    setTimeout(function(){
      component.set('things', ['apple', 'banana', 'carrot'])
    }, 5 * 1000)
  }
});

唯一的问题是,由于ractive重用元素,因此样式显示在错误的元素上。

您会看到当'banana', 'carrot']更改为['apple', 'banana', 'carrot'] ,突出显示了'carrot'元素,而不是与新的对应的'apple'元素值。

在数组中设置新条目样式的最佳方法是什么?

您应该使用splice方法

 component.splice('things', 0, 0, 'apple');   // Add at zero index   
 component.splice('things', 1, 0, 'apple');   // Add at first index  

而不是再次设置整个数组。 这等效于Array.splice方法。

整个代码将如下所示。

var ractive = new Ractive({
  el: 'main',
  template: `
    <h1>Hello {{name}}!</h1>

    {{ #things:index }}
        <p>{{ things[index] }}</p>  
    {{ /things }}

  `,
  data: function(){
    return {
        things: [
        'banana',
        'carrot'
      ]
    }
  },
  oncomplete: function(){
    var component = this;

    setTimeout(function(){    
        component.splice('things', 0, 0, 'apple');
    }, 5 * 1000)
  }
});

在此处了解更多信息。
https://ractive.js.org/api/#ractivesplice

使用recentlyAddedThings添加的东西缓存来添加已添加项目的缓存。 这是一个工作的jsfiddle

var ractive = new Ractive({
  el: 'main',
  template: `

    {{ #things:index }}

      <p class="{{ #if recentlyAddedThings.includes(things[index]) }}new{{ /if }}">
        {{ things[index] }}
      </p>  
    {{ /things }}

  `,
  data: function(){
    return {
      things: [
        'banana',
        'carrot'
      ],
      recentlyAddedThings: [

      ]
    }
  },
  oncomplete: function(){
    var component = this;

    var addThing = function(newThing){
      var things = component.get('things')
      var newThing = newThing
      things.push(newThing)
      component.set('things', things.sort())
      component.push('recentlyAddedThings', newThing)
    }

    setTimeout(function(){
      addThing('apple') 
    }, 2 * 1000)
    setTimeout(function(){
      addThing('avocado') 
    }, 3 * 1000)
    setTimeout(function(){
      addThing('cheese')  
    }, 4 * 1000)
  }
});

暂无
暂无

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

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