JavaScript/vue.js/一个简单组件的调试过程

来自康健生活
Kangkk​(留言 | 贡献)2020年9月14日 (一) 08:50的版本 (→引言)

引言

有一个很有意思的事情是我想把一个分类标签抽离出来,它可以使 1 行 n 列,也可以是 n 行 n 列。

实现效果如下(这里是 3 行 n 列):

动态赋值 data 展示效果图
动态赋值 data 展示效果图

实例中每点击一次按钮会出现一次闪烁,这个闪烁是因为每次点击都是重新从服务端下载一次资源,然后加载渲染(并不是点击之后页面组件重新填充数据),这么做是因为后期需要将页面缓存,所以设计的时候做的是服务端渲染数据(SSR),每一个操作行为都将可能是拉取一个新的页面。针对这个情况可以将标签内容在离开页面之前监听 beforeunload 将标签 data 存入 session,重新进入页面时监听 DOMContentLoaded 或者 load 将 session 中的数据填充。

再动态赋值的过程中,子组件是一个黑盒,我不知道有几行几列,有哪些字段和那些值,只是按照固定的传入数据格式进行填充数据。

父组件调用

父组件.vue
<!-- @auther kangkk
  @date
  @desc -->
<template>
  <div class="lattice-width">
    <PageNavMenu @noticeCategoryValue="noticeTabValue"/>
    <ComCategory :list="sortList"
                 @noticeCategoryValue="noticeCategoryValue"/>
    </el-row>
  </div>
</template>

<script>
  import PageNavMenu from '@/pages/search/navmenu.vue'
  import ComCategory from '@@/components/navmenu/category.vue'

  export default {
    data () {
      return {
        sortList:[
          {
            name: '综合排序',
            enName: 'mixedPriorities',
            default: this.$route.params.mixedPriorities || 'latestRelease',
            child:[{name:'最新发布',key:'latestRelease'},{name:'最新修改',key:'latestUpdate'},{name:'最多下载',key:'mostDownload'},{name:'最多点赞',key:'mostVote'},{name:'最多收藏',key:'mostCollect'},{name:'价格升序',key:'costAscending'},{name:'最多评论',key:'mostComment'}]
          },
          {
            name: '全部作品',
            enName: 'allOeuvre',
            default: this.$route.params.allOeuvre || 'free',
            child:[{name:'免费',key:'free'},{name:'收费',key:'charge'}]
          },
          {
            name: '全部分类',
            enName: 'all',
            default: this.$route.params.all || 'cs',
            child:[{name:'计算机/软件',key:'cs'},{name:'机械/机电',key:'mem'},{name:'电子/通信',key:'et'},{name:'电气/控制',key:'ec'},{name:'土木/建筑',key:'cea'},{name:'可视化/交互',key:'vi'},{name:'其他',key:'other'}]
          }
        ]
      }
    },

    components: {
      PageNavMenu,
      ComCategory,
    },
    methods: {
      noticeCategoryValue (data) {
        // todo
      },
      noticeTabValue (data) {
        // todo
      },
    }
  }
</script>

子组件

@@/components/navmenu/category.vue
<template>
  <article :class="$nav_category.container">
    <div v-for="(item) in list"
         :key="item.enName"
         class="clear-fix"
         :class="$nav_category.list">
      <div class="left"
           :class="$nav_category.title">
        {{ item.name }}
      </div>
      <div class="left"
           :class="$nav_category.box">
        <el-radio-group v-for="child in item.child"
                        :key="child.key"
                        v-model="item.default"
                        class="eu-nav-category__list-btn"
                        @change.native="noticeValueChange(item.enName, child.key)">
          <el-radio-button :label="child.key">{{ child.name }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
  </article>
</template>
<style module="$nav_category" lang="scss">@import "./category";</style>
<script>
  export default {
    name: 'ComCategory',
    data () {
      // 动态赋值 data
      const tmpKeyList = this.list.map(o=>{return o.enName})
      let tmpPropObj = {}
      tmpPropObj['allPropsKey'] = tmpKeyList
      return tmpPropObj
    },
    props: {
      list: {
        type: Array,
        default: () => []
      }
    },
    methods: {
      noticeValueChange (itemEnName,childName) {
        let tmpPropObj = {}
        for(let i=0;i<this.allPropsKey.length;i++){
          if(this.allPropsKey[i] === itemEnName){
            tmpPropObj[this.allPropsKey[i]] = childName
          }
        }
        this.$emit('noticeCategoryValue',tmpPropObj)
      }
    }
  }
</script>

这个简单组件的思想就是利用 data 或者 computed 缓存以一级标签的 key 作为标识,用于触发点击时发送正确的一级标签和二级标签值。如果按照函数编程的思想 noticeValueChange 可以更改为

methods: {
  noticeValueChange (itemEnName,childName) {
    let tmpPropObj = {}
    const index = this.allPropsKey.findIndex(o=> o === itemEnName)
    tmpPropObj[this.allPropsKey[index]] = childName
    this.$emit('noticeCategoryValue',tmpPropObj)
  }
}

但如果仔细看的话,在这个组件中的动态赋值是多余的,因为按照上例其实是这样:

methods: {
  noticeValueChange (itemEnName,childName) {
    let tmpPropObj = {}
    tmpPropObj[itemEnName] = childName
    this.$emit('noticeCategoryValue',tmpPropObj)
  }
}

再简化一下:

methods: {
  noticeValueChange (itemEnName,childName) {
    this.$emit('noticeCategoryValue',{[itemEnName]:childName})
  }
}

但这里我要说的是如何合理的动态的缓存值并留待为复杂逻辑进行扩展,如果只是按照上例的简单应用,是可以删掉其他代码,只留下 this.$emit('noticeCategoryValue',{[itemEnName]:childName}) 就可以了。

比如我现在要添加一个需求,在分类栏上面新加一个标签栏,标签栏限定分类栏,如果选择问答就让其中一个或多个二级标签或者一级标签以及全部其下二级标签变灰色且不可点击,这和时候就需要前题所说的动态复制 data 来缓存一部分数据了:

第一阶段代码:

父组件.vue
<!-- @auther kangkk
  @date 
  @desc  -->
<template>
  <div class="lattice-width">
    <PageNavMenu @noticeCategoryValue="noticeTabValue"/>
    <ComCategory :list="sortList"
                 :disClickFilter="filterCategoryClick"
                 @noticeCategoryValue="noticeCategoryValue"/>
  </div>
</template>

<script>
  import PageNavMenu from '@/pages/search/navmenu.vue'
  import ComCategory from '@@/components/navmenu/category.vue'

  export default {
    name: 'Search',
    data () {
      return {
        searchPageViewValue: 'searchAll',
        sortList:[
          {
            name: '综合排序',
            enName: 'mixedPriorities',
            default: this.$route.params.mixedPriorities || 'latestRelease',
            child:[{name:'最新发布',key:'latestRelease'},{name:'最新修改',key:'latestUpdate'},{name:'最多下载',key:'mostDownload'},{name:'最多点赞',key:'mostVote'},{name:'最多收藏',key:'mostCollect'},{name:'价格升序',key:'costAscending'},{name:'最多评论',key:'mostComment'}]
          },
          {
            name: '全部作品',
            enName: 'allOeuvre',
            default: this.$route.params.allOeuvre || 'free',
            child:[{name:'免费',key:'free'},{name:'收费',key:'charge'}]
          },
          {
            name: '全部分类',
            enName: 'all',
            default: this.$route.params.all || 'cs',
            child:[{name:'计算机/软件',key:'cs'},{name:'机械/机电',key:'mem'},{name:'电子/通信',key:'et'},{name:'电气/控制',key:'ec'},{name:'土木/建筑',key:'cea'},{name:'可视化/交互',key:'vi'},{name:'其他',key:'other'}]
          }
        ]
      }
    },

    components: {
      PageNavMenu,
      ComCategory,
    },
    methods: {
      filterCategoryClick (obj){
        if(this.$route.params.tab === 'qa') {
          // 以二级标签为锚点
          return Object.keys(obj)[0] === 'allOeuvre'
        }
      },
      noticeCategoryValue (data) {
        this.$store.dispatch('pagination/setPagination', {
          currentPage: 1,
          data: Object.assign({}, this.$store.state.pagination.data, data)
        })
        this.toHref()
      },
      noticeTabValue (data) {
        this.$store.dispatch('pagination/setPagination', {
          currentPage: 1,
          data: Object.assign({}, this.$store.state.pagination.data, data)
        })
        this.toHref()
      },
    }
  }
</script>

子组件

@@/components/navmenu/category.vue
<template>
  <article :class="$nav_category.container">
    <div v-for="(item, index) in list"
         :key="item.enName"
         class="clear-fix"
         :class="[$nav_category.list]">
      <div class="left"
           :class="[$nav_category.title,{[$nav_category.disClick]:(allPropsKey[index].count <= allPropsKey[index].index)}]">
        {{ item.name }}
      </div>
      <div class="left"
           :class="$nav_category.box">
        <el-radio-group v-for="child in item.child"
                        :key="child.key"
                        v-model="item.default"
                        :class="{[$nav_category.disClick]:isDisClick(item.enName, child.key)}"
                        class="eu-nav-category__list-btn"
                        @change.native="noticeValueChange(item.enName, child.key)">
          <el-radio-button :label="child.key">{{ child.name }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
  </article>
</template>
<style module="$nav_category" lang="scss">@import "./category";</style>
<script>
  export default {
    name: 'ComCategory',

    data () {
      // 动态赋值 data
      const tmpKeyList = this.list.map(o=>{return {name: o.enName, count: o.child.length, index: 0}})
      let tmpPropObj = {}
      tmpPropObj['allPropsKey'] = tmpKeyList
      return tmpPropObj
    },
    components: {},
    props: {
      disClickFilter:{
        type: Function,
        default: () => function (){}
      },
      list: {
        type: Array,
        default: () => []
      },
    },
    methods: {
      noticeValueChange (itemEnName,childName) {
        this.$emit('noticeCategoryValue', {[itemEnName]:childName})
      },
      isDisClick (itemEnName,childName){
        // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
        const cb = this.disClickFilter({[itemEnName]:childName})
        if(cb){
          const index = this.allPropsKey.findIndex(o=> o.name===itemEnName)
          // 每次 allPropsKey 数据更改都会重新触发渲染,所以添加限定条件让其在有序的情况下触发渲染
          if(this.allPropsKey[index].index <= this.allPropsKey[index].count){
            this.allPropsKey[index].index++
          }
        }
        return cb
      },
    }
  }
</script>

效果图如下:

动态复制 data
动态复制 data

动图中可以看出效果是实现的,但是一级标签变灰会有延迟,这是由于我在代码里将一级标签的变灰判断放在了 html 标签中进行判断,这个判断是延迟的,要在所有二级标签判断结束之后。并且由于最初的设计是父组件传入子组件是 n*n,参数未知,所以很难设置 computed 计算每个一级标签的状态,所以付出了二级标签判断方法中,每命中一次,都会由于 data 的值变化触发重新渲染,造成了性能损失(可以设定条件在有序范围内触发,减少损失)。

针对这一问题,使用一种规避的方法(因为是 n*n,不好定位每一个一级标签以及一级标签的标识,所以放弃使用计算属性),使用组件内的全局参数作为计数器,更改代码如下: 子组件

@@/components/navmenu/category.vue
<template>
  <article :class="$nav_category.container">
    <div v-for="(item, index) in list"
         :key="item.enName"
         class="clear-fix"
         :class="[$nav_category.list]">
      <div :ref="'itemTitle'+index"
           class="left"
           :class="[$nav_category.title]">
        {{ item.name }}
      </div>
      <div class="left"
           :class="$nav_category.box">
        <el-radio-group v-for="child in item.child"
                        :key="child.key"
                        v-model="item.default"
                        :class="{[$nav_category.disClick]:isDisClick(item.enName, child.key)}"
                        class="eu-nav-category__list-btn"
                        @change.native="noticeValueChange(item.enName, child.key)">
          <el-radio-button :label="child.key">{{ child.name }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
  </article>
</template>
<style module="$nav_category" lang="scss">@import "./category";</style>
<script>
  let itemCountArr = []; // 元素计数器数组
  export default {
    name: 'ComCategory',

    data () {
      // 动态赋值 data
      const tmpKeyList = this.list.map(o=>{itemCountArr.push(0);return {name: o.enName, count: o.child.length}})
      let tmpPropObj = {}
      tmpPropObj['allPropsKey'] = tmpKeyList
      return tmpPropObj
    },
    components: {},
    props: {
      disClickFilter:{
        type: Function,
        default: () => function (){}
      },
      list: {
        type: Array,
        default: () => []
      },
    },
    methods: {
      noticeValueChange (itemEnName,childName) {
        this.$emit('noticeCategoryValue', {[itemEnName]:childName})
      },
      isDisClick (itemEnName,childName){
        // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
        const cb = this.disClickFilter({[itemEnName]:childName})
        if(cb){
          const index = this.allPropsKey.findIndex(o=> o.name===itemEnName)
          // 每次 allPropsKey 数据更改都会重新触发渲染,所以添加限定条件让其在有序的情况下触发渲染
          if(itemCountArr[index] < this.allPropsKey[index].count){
            itemCountArr[index]++
            if(this.allPropsKey[index].count <= itemCountArr[index]){
              this.$nextTick(() => {
                if(this.$refs['itemTitle'+index]){
                  this.$refs['itemTitle'+index][0].classList.add("active")
                }
              });
            }
          }
        }
        return cb
      },
    }
  }
</script>
<style lang="scss">
.eu-nav-category__list-btn {
  .el-radio-button__inner {
    padding: 5px 10px;
    margin-left: 0;
    margin-right: 10px;
    border: none;
    border-left: none !important;
  }
}
.active{
  background: red;
}
</style>

效果如图:

vue 动态赋值 data
vue 动态赋值 data

改了一版,还有一个 bug 没解决,留待明后天修改

<template>
  <article :class="$nav_category.container">
    <div v-for="(item, index) in list"
         :key="item.enName"
         class="clear-fix"
         :class="[$nav_category.list]">
      <div class="left"
           :class="[$nav_category.title,{[$nav_category.disClick]:isShowGrayBgColor(index, item.enName)}]">
        {{ item.name }}
      </div>
      <div class="left"
           :class="$nav_category.box">
        <el-radio-group v-for="child in item.child"
                        :key="child.key"
                        v-model="item.default"
                        :class="{[$nav_category.disClick]:isDisClick(item.enName, child.key)}"
                        class="eu-nav-category__list-btn"
                        @change.native="noticeValueChange(item.enName, child.key)">
          <el-radio-button :label="child.key">{{ child.name }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
  </article>
</template>
<style module="$nav_category" lang="scss">@import "./category";</style>
<script>
  export default {
    name: 'ComCategory',

    data () {
      // 动态赋值 data
      const tmpKeyList = this.list.map(o=>{return {name: o.enName, count: o.child.length}})
      let tmpPropObj = {}
      tmpPropObj['allPropsKey'] = tmpKeyList
      return tmpPropObj
    },
    components: {},
    props: {
      disClickFilter:{
        type: Function,
        default: () => function (){}
      },
      list: {
        type: Array,
        default: () => []
      },
    },
    computed: {
      cloneAllPropsKeyIndex (){
        return [...this.allPropsKey.map(()=>{return 0})]
      },
      isShowGrayBgColor () {
        return function (index) {
          return this.allPropsKey[index].count <= this.cloneAllPropsKeyIndex[index]
        }
      },
    },
    methods: {
      noticeValueChange (itemEnName,childName) {
        this.$emit('noticeCategoryValue', {[itemEnName]:childName})
      },
      isDisClick (itemEnName,childName){
        // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
        const cb = this.disClickFilter({[itemEnName]:childName})
        if(cb){
          const index = this.allPropsKey.findIndex(o=> o.name===itemEnName)
          // 每次 allPropsKey 数据更改都会重新触发渲染,所以添加限定条件让其在有序的情况下触发渲染
          if(this.cloneAllPropsKeyIndex[index] < this.allPropsKey[index].count){
            this.cloneAllPropsKeyIndex[index]++
          }
        }
        return cb
      }
    }
  }
</script>

计算属性依赖于内部的依赖的变化,组件的最终目的是要解决一级标签样式延迟(判断语句延迟)的问题,前置条件是用现有的自定义的 filter 方法,不再做过多的添加以免冗余。所以,晚安,世界~。

更新一版,解决 You may have an infinite update loop in a component render function 渲染死循环的问题,一级标签的数据绑定按照逻辑应该很快就会执行,但是实际上它是依赖于数据传递过来并且放到 data 中的数据的,所以看动图会发现有一个顿卡的画面,

<template>
  <article :class="$nav_category.container">
    <div v-for="(item, index) in list"
         :key="item.enName"
         class="clear-fix"
         :class="[$nav_category.list]">
      <div class="left"
           :class="[$nav_category.title,{[$nav_category.disClick]:allPropsKey[index].status}]">
        {{ item.name }}
      </div>
      <div class="left"
           :class="$nav_category.box">
        <el-radio-group v-for="child in item.child"
                        :key="child.key"
                        v-model="item.default"
                        :class="{[$nav_category.disClick]:isDisClick(item.enName, child.key)}"
                        class="eu-nav-category__list-btn"
                        @change.native="noticeValueChange(item.enName, child.key)">
          <el-radio-button :label="child.key">{{ child.name }}</el-radio-button>
        </el-radio-group>
      </div>
    </div>
  </article>
</template>
<style module="$nav_category" lang="scss">@import "./category";</style>
<script>
  export default {
    name: 'ComCategory',

    data () {
      // 动态赋值 data
      const tmpKeyList = this.list.map(o=>{return {name: o.enName, count: o.child.length, index: 0, status: false}})
      let tmpPropObj = {}
      tmpPropObj['allPropsKey'] = tmpKeyList
      tmpPropObj['tmpIndexArr'] = new Array(this.list.length).fill(0)
      return tmpPropObj
    },
    components: {},
    props: {
      disClickFilter:{
        type: Function,
        default: () => function (){}
      },
      list: {
        type: Array,
        default: () => []
      },
    },
    computed: {
      cloneAllPropsKeyIndex :{
        get (){
          // return [...this.allPropsKey.slice().map(o=>{return o.index})]
          return this.tmpIndexArr.slice()
        },
        set (index){
          this.tmpIndexArr[index]++
          if(this.allPropsKey[index].count <= this.tmpIndexArr[index]){
            this.allPropsKey[index].status = true
          }
        }
      },
    },
    methods: {
      noticeValueChange (itemEnName,childName) {
        this.$emit('noticeCategoryValue', {[itemEnName]:childName})
      },
      isDisClick (itemEnName,childName){
        // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
        const cb = this.disClickFilter({[itemEnName]:childName})
        if(cb){
          this.cloneAllPropsKeyIndex = this.allPropsKey.findIndex(o=> o.name===itemEnName)
        }
        return cb
      }
    }
  }
</script>

写到这里已经跑题了,本意是想表述一个动态赋值的事情,结果演变成写一个子组件的问题排查分析。更关键的是我还没有找到一个合理的解决一级标签顿卡的方法。

留待后续更新。

这里涉及的是数据渲染的过程,

使用一种非主流的方法,尽量缩短数据渲染的时间

<template>
...
      <div class="left"
           :class="[$nav_category.title,{[$nav_category.disClick]:allPropsKey[index].status}]">
...
        <el-radio-group v-for="child in item.child"
...
                        :class="{[$nav_category.disClick]:isDisClick(item.enName, child.key)}"
...
</template>
<style module="$nav_category" lang="scss">@import "./category";</style>
<script>
...
    computed: {
      cloneAllPropsKeyIndex :{
        get (){
          return this.tmpIndexArr.slice()
        },
        set (index){
          this.tmpIndexArr[index]++
          if(this.allPropsKey[index].count <= this.tmpIndexArr[index]){
            const _that = this
            setTimeout(function (){
              _that.allPropsKey[index].status = true
            },0.01)
          }
        }
      },
    },
    watch:{
      allPropsKey:{
        handler (newVal, oldVal) {
        },
        deep: true
      }
    },
    ...
      isDisClick (itemEnName,childName){
        // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
        const index = this.allPropsKey.findIndex(o=> o.name===itemEnName)
        const cb = this.disClickFilter({[itemEnName]:childName})
        if(cb && this.allPropsKey[index].status !== true){
          this.cloneAllPropsKeyIndex = index
...

使用 moment 打出时间点,分析数据流通过程

Snipaste 2020-09-14 12-41-28
Snipaste 2020-09-14 12-41-28

在之前的动图中我们观察到二级标签和一级标签之间渲染间隔很大,二级标签几乎瞬间渲染,而在打出的时间点里,一级标签和二级标签的背景更改状态时间间隔只有 1 微秒,所以一定是有个流程代码有错误导致顿卡。

在图示中紫色涂卡笔标注的地方是由于,一级标签的 status 发生改变(存于 data 并且绑定了节点),组件重新渲染,所以又加载了每个绑定了 methods 中的方法的标签,重新执行了一次函数。这里为什么不用事件委托,在 vue 等主流框架一般都会将事件逐级冒泡并绑定在 body 上,还不清楚 vue 有没有类似处理,关键是这个组件的事件绑定在父节点,而绑定值如果绑定在 element-ui 组件上,但实际上出发事件的是 element-ui 组件内部的标签并且做了阻止事件冒泡处理,导致组件父节点拿不到绑定值,总之处理起来很麻烦。

最新的效果图:

Honeycam 2020-09-14 15-46-54
Honeycam 2020-09-14 15-46-54