JavaScript/vue.js/一个简单组件的调试过程:修订间差异

来自康健生活
Kangkk​(留言 | 贡献)
Kangkk​(留言 | 贡献)
 
(未显示同一用户的14个中间版本)
第156行: 第156行:
methods: {
methods: {
   noticeValueChange (itemEnName,childName) {
   noticeValueChange (itemEnName,childName) {
     this.$emit('noticeCategoryValue',new Object({[itemEnName]:childName}))
     this.$emit('noticeCategoryValue',{[itemEnName]:childName})
   }
   }
}
}
第162行: 第162行:


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


比如我现在要添加一个需求,在分类栏上面新加一个标签栏,标签栏限定分类栏,如果选择<code>问答</code>就让其中一个或多个二级标签或者一级标签以及全部其下二级标签变灰色且不可点击,这和时候就需要前题所说的动态复制 data 来缓存一部分数据了:
比如我现在要添加一个需求,在分类栏上面新加一个标签栏,标签栏限定分类栏,如果选择<code>问答</code>就让其中一个或多个二级标签或者一级标签以及全部其下二级标签变灰色且不可点击,这和时候就需要前题所说的动态复制 data 来缓存一部分数据了:
第293行: 第293行:
     methods: {
     methods: {
       noticeValueChange (itemEnName,childName) {
       noticeValueChange (itemEnName,childName) {
         this.$emit('noticeCategoryValue', Object({[itemEnName]:childName}))
         this.$emit('noticeCategoryValue', {[itemEnName]:childName})
       },
       },
       isDisClick (itemEnName,childName){
       isDisClick (itemEnName,childName){
         // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
         // 判断二级标签背景状态,以二级标签为锚点,如果只是二级标签中其中一个命中,一级标签不做改变,如果二级标签全部命中,一级标签背景改变
         const cb = this.disClickFilter(Object({[itemEnName]:childName}))
         const cb = this.disClickFilter({[itemEnName]:childName})
        console.log(cb)
         if(cb){
         if(cb){
           const index = this.allPropsKey.findIndex(o=> o.name===itemEnName)
           const index = this.allPropsKey.findIndex(o=> o.name===itemEnName)
第305行: 第304行:
             this.allPropsKey[index].index++
             this.allPropsKey[index].index++
           }
           }
          console.log(this.allPropsKey[index].index)
         }
         }
         return cb
         return cb
第318行: 第316行:
[[文件:Honeycam 2020-09-13 22-21-19.gif|600px|none|无|动态复制 data]]
[[文件:Honeycam 2020-09-13 22-21-19.gif|600px|none|无|动态复制 data]]


动图中可以看出效果是实现的,但是一级标签变灰会有延迟,
动图中可以看出效果是实现的,但是一级标签变灰会有延迟,这是由于我在代码里将一级标签的变灰判断放在了 html 标签中进行判断,这个判断是延迟的,要在所有二级标签判断结束之后。并且由于最初的设计是父组件传入子组件是 <code>n*n</code>,参数未知,所以很难设置 <code>computed</code> 计算每个一级标签的状态,所以付出了二级标签判断方法中,每命中一次,都会由于 data 的值变化触发重新渲染,造成了性能损失(可以设定条件在有序范围内触发,减少损失)。
 
针对这一问题,使用一种规避的方法(因为是 <code>n*n</code>,不好定位每一个一级标签以及一级标签的标识,所以放弃使用计算属性),使用组件内的全局参数作为计数器,更改代码如下:
子组件
{{hc|head=@@/components/navmenu/category.vue|output=<syntaxhighlight lang="html">
<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>
</syntaxhighlight>}}
 
效果如图:
 
[[文件:Honeycam 2020-09-13 23-51-42.gif|600px|none|无|vue 动态赋值 data]]
 
改了一版,还有一个 bug 没解决,留待明后天修改
<syntaxhighlight lang="javascript">
<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></syntaxhighlight>
 
计算属性依赖于内部的依赖的变化,组件的最终目的是要解决一级标签样式延迟(判断语句延迟)的问题,前置条件是用现有的自定义的 filter 方法,不再做过多的添加以免冗余。所以,晚安,世界~。
 
更新一版,解决 <code>You may have an infinite update loop in a component render function</code> 渲染死循环的问题,一级标签的数据绑定按照逻辑应该很快就会执行,但是实际上它是依赖于数据传递过来并且放到 data 中的数据的,所以看动图会发现有一个顿卡的画面,
 
<syntaxhighlight lang="javascript">
<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></syntaxhighlight>
写到这里已经跑题了,本意是想表述一个动态赋值的事情,结果演变成写一个子组件的问题排查分析。更关键的是我还没有找到一个合理的解决一级标签顿卡的方法。
 
留待后续更新。
 
这里涉及的是数据渲染的过程,
 
使用一种非主流的方法,尽量缩短数据渲染的时间
<syntaxhighlight lang="html5" highlight="23,24,25">
<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
...</syntaxhighlight>
 
使用 moment 打出时间点,分析数据流通过程
 
[[文件:Snipaste 2020-09-14 12-41-28.png|500px|none|无|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.gif|600px|none|无|Honeycam 2020-09-14 15-46-54]]