vue移動端引用第三方組件-lytab(學習筆記)

網絡上有個大神自己寫了一個移動端可滑動(慣性滑動&回彈)Vue導航欄組件 ly-tab
然後我想把它用到我的項目中去,發現會有這個報錯:SyntaxError: Unexpected token import
我也不知道是哪個步驟操作不正確。我就把它的源碼從node_modules文件中複製出來,放在components文件下

node_modules
clipboard.png
components
clipboard.png

在需要使用的組件中局部引用

import LyTab from '@/components/Scroll'

後來我發現還是報SyntaxError: Unexpected token import
接着嘗試把路徑換成下面的就不會報錯了

import LyTab from '@/components/Scroll/src/index.vue'

==========================================運用======================================

<ly-tab :items="sortList" :options="options" class="parent" v-model="selected"></ly-tab>
items是傳遞給子組件的數組
options是lytab的配置
export default {
  components: {
    LyTab
  },
  data() {
    return {
      sortList: [], //父分類
      i: 0,
      selected: 0,
      options: {
        activeColor: '#78d5f7',
        labelKey: 'name' // 在sortList數組中選擇想要渲染的key名
      }
    }
  }
}

後面我需要去獲取點擊父分類的index值從而篩選子分類,所以我需要在源碼的基礎添加
index.vue子組件

<template>
  <div class="ly-tab">
    <ly-tabbar v-bind="options" v-model="selectedId">
      <ly-tab-item :key="index" v-for="(item, index) in items">
        <span slot="icon" v-if="options.fixBottom && item.icon">
          <i :class="item.icon"></i>
        </span>
        <span @click="getindex(index)">{{ item[labelKey] }}</span>
      </ly-tab-item>
    </ly-tabbar>
  </div>
</template>

新增getindex函數獲取點擊的index然後傳遞給父組件

父組件接收

<ly-tab :items="sortList" :options="options" @parent="parent" class="parent" v-model="selected"></ly-tab>
<div class="child" v-if="sortList[i].subCategoryList.length>0">
  <ul>
    <nuxt-link
      :key="index"
      :to="{path: '/quesbank/sort', query: {cp_id: item.pid, c_id: item.id}}"
      v-for="(item,index) of sortList[i].subCategoryList"
    >
      <li
        :class="$route.query.c_id===item.id?'activechild':''"
        v-if="item.name!==''"
      >{{item.name}}</li>
    </nuxt-link>
  </ul>
</div>
export default {
  components: {
    LyTab
  },
  data() {
    return {
      sortList: [], //父分類
      i: 0,
      selected: 0,
      options: {
        activeColor: '#78d5f7',
        labelKey: 'name'
      }
    }
  },
  mounted() {
    if (this.$route.query.cp_id) {
      this.selected = Number(this.$route.query.cp_id)
    }
  },
  //asyncData在服務端渲染
  async asyncData() {
    let res = await Net.getSort()
    let result = res.data.data
    result.unshift({
      name: '全部',
      id: 0,
      subCategoryList: []
    })
    for (let i = 0; i < result.length; i++) {
      if (result[i].subCategoryList) {
        for (let j = 0; j < result[i].subCategoryList.length; j++) {
          result[0].subCategoryList.push(result[i].subCategoryList[j])
        }
      }
    }
    result[0].subCategoryList.unshift({
      name: '全部',
      id: 0,
      pid: 0
    })
    return {
      sortList: result
    }
  },
  methods: {
  //獲取index進行子分類的篩選
    parent(index) {
      this.i = index
    }
  }
}
</script>

寫的很亂,是自己平時項目中的小總結

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章