linche0859
9/16/2019 - 3:14 PM

資料巢狀分類

HTML

<div id="app">
  類型 :
  <select v-model="input.type" style="margin: 5px;">
    <option :value="null">請選擇</option>
    <option v-for="type in typeList.sort">{{ type }}</option>
  </select>
  <br />
  標題 :
  <select v-model="input.title" style="margin: 5px;">
    <option :value="null">請選擇</option>
    <option v-for="title in titleList.sort">{{ title }}</option>
  </select>
  <br />
  <p>內容 : <a v-if="content" :href="content.link">{{ content.link }}</a></p>
</div>

Javascript

const data = {
  courses: [
    { type: '第一課', title: '第一課之一', link: '第一課之一Url:;' },
    { type: '第一課', title: '第一課之二', link: '第一課之二Url:;' },
    { type: '第二課', title: '第二課之一', link: '第二課之一Url:;' },
    { type: '第二課', title: '第二課之二', link: '第二課之二Url:;' },
    { type: '第二課', title: '第二課之三', link: '第二課之三Url:;' },
    { type: '第三課', title: '第三課之一', link: '第三課之一Url:;' },
    { type: '第三課', title: '第三課之二', link: '第三課之二Url:;' },
    { type: '第四課', title: '第四課之一', link: '第四課之一Url:;' },
    { type: '第四課', title: '第四課之二', link: '第四課之二Url:;' },
    { type: '第四課', title: '第四課之三', link: '第四課之三Url:;' }
  ],
  input: {
    type: null,
    title: null
  }
}

new Vue({
  el: '#app',
  data: data,
  computed: {
    typeList() {
      // 巢狀放入
      let obj = {
        // 放入type、title不重複資料
        sort: [],
        // 放入type 對應的title
        // 或title 對應的link
        map: {}
      }
      this.courses.forEach(({ type, title, link }, index) => {
        if (!obj.map[type]) {
          obj.sort.push(type)
          obj.map[type] = {
            sort: [],
            map: {}
          }
        }
        obj.map[type].sort.push(title)
        obj.map[type].map[title] = { link }
      })
      return obj
    },
    titleList() {
      this.input.title = null
      if (this.input.type) {
        return this.typeList.map[this.input.type]
      } else return []
    },
    content() {
      if (this.input.title) {
        return this.titleList.map[this.input.title]
      } else return null
    }
  }
})