簡體   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