具有动态子元素数量的Vue组件

时间:2018-11-08 02:17:00

标签: vuejs2

我正在显示用数组(动态长度)替换的字符串列表。我想显示使用span或其他元素替换为不同颜色的每个字符串。我的代码显示了我所需要的,但是我不喜欢使用v-html。我想为每个“ li”创建一个组件。有更好的方法吗?

代码:https://jsfiddle.net/dowhiledo/jw98kfus/

var example1 = new Vue({
  el: '#example',
  data: {
    items: [{
        str: 'This is ### an he is ### years old',
        list: ['Frank', '14']
      },
      {
        str: '### and ### are ### ',
        list: ['George', 'John', "studying"]
      }
    ],

  },
  computed: {
    replaced() {
      this.items.forEach(item => {
        item.newStr = item.str;
        item.list.forEach(s => {
          item.newStr = item.newStr.replace("###", s)
        })
      })
      return this.items
    },
  },
  methods: {
    replaced2(item) {
      item.newStr2 = item.str;
      var count = 1;
      item.list.forEach(s => {
        var newElem = "<span class=span"+count+">" + s + "</span>";
        item.newStr2 = item.newStr2.replace("###", newElem)
        count++;
      })
      return item.newStr2
    }
  }
});
.span1 {  color: blueviolet;}
.span2 {  color: green;}
.span3 {  color: red;}
.span4 {  color: purple;}
.span5 {  color: yellow;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.min.js"></script>
<div id="example">
  <ul>
    <li v-for="(item,i) in replaced">
      {{ item.newStr }}
    </li>
  </ul>


  <hr> This is what I need:
  

  <ul>
    <li v-for="(item,i) in items" v-html="replaced2(item)">
    </li>
  </ul>

</div>

0 个答案:

没有答案