VueJS-根据数据自动创建A-Z字母列表

时间:2019-07-16 09:16:51

标签: vue.js

是否可以根据API和Vue中的数据创建A-Z字母列表(like this),以便能够确定数据中的属性是否包含以哪个字母开头的名称。如果数据中没有特定的字母名称,则从字母锚标记中删除/禁用href属性。

在链接的示例中,字母K,X和Z缺少坐标,因为它们没有数据

JSON

[
    {
        "id": 77,
        "link": "http://my-site/cosmoquotes/authors/anonymous/",
        "name": "Anonymous",
        "slug": "anonymous"
    },
    {
        "id": 72,
        "link": "http://my-site/authors/ferdinand-marcos/",
        "name": "Ferdinand Marcos",
        "slug": "ferdinand-marcos"
    },
    {
        "id": 75,
        "link": "http://my-site/authors/john-f-kennedy/",
        "name": "John F. Kennedy",
        "slug": "john-f-kennedy"
    },
    {
        "id": 67,
        "link": "http://my-site/authors/john-maxwell/",
        "name": "John Maxwell",
        "slug": "john-maxwell"
    }
]

组件

export default {
  data() {
    return {
      authorsRequest: {
        type: 'authors',
        params: {
          per_page: 100
        }
      },
    }
  },

  computed: {
    authors () {
      return this.$store.getters.requestedItems(this.authorsRequest)
    },
  },
  methods: {
    getAuthors() {
      return this.$store.dispatch('getItems', this.authorsRequest)
    },
  },
  created() {
    this.getAuthors()
  }
}

因此,根据返回的数据,仅可单击/显示字母“ A”,“ F”和“ J”。

2 个答案:

答案 0 :(得分:1)

我设法做到了这一点, 不幸的是,它需要authors数组和条件函数在Vue组件之外,因为我找不到如何将参数传递给计算值 但是由于我是vue的新手(甚至还没有读完介绍),所以我确定必须有一个更好的解决方案


编辑:使用methods找到了在组件中具有功能的方法,然后我也可以在组件中移动数据

let a = new Vue({
  el: "#selector",
  data: {
    authors: [{"id": 77,"link": "http://my-site/cosmoquotes/authors/anonymous/","name": "Anonymous","slug": "anonymous"},{"id": 72,"link": "http://my-site/authors/ferdinand-marcos/","name": "Ferdinand Marcos","slug": "ferdinand-marcos"},{"id": 75,"link": "http://my-site/authors/john-f-kennedy/","name": "John F. Kennedy","slug": "john-f-kennedy"},{"id": 67,"link": "http://my-site/authors/john-maxwell/","name": "John Maxwell","slug": "john-maxwell"}]
  },
  computed: {
    // there have to be a way to get this array without doing it like this but I don't know it ^^
    letters() {
      let letters = []
      for(let i = "A".charCodeAt(0); i <= "Z".charCodeAt(0); i++) {letters.push(String.fromCharCode([i]))}
      return letters
    }
  },
  methods: {
    // you may add a toUpperCase()/toLowerCase() if you're not sure of the capitalisation of you datas
    isALink(letter) {
      return this.authors.some(aut => aut.name.startsWith(letter))
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>

<div id="selector">
  <template v-for="letter in letters">
    <a v-if="isALink(letter)" :href="letter">{{ letter }}</a>
    <a v-else>{{ letter }}</a>
  </template>
</div>

答案 1 :(得分:0)

您可以将唯一名称设置为dom的ID。单击字母X时,只需获得以X开头的名字,并使用getElementById匹配dom并滚动到dom。