vue 父子组件传数组, computed与watch都无法触发

新手上路,请多包涵

问题描述

  1. 分类树状表格, 异步加载数据; 子组件向父组件发送事件, 父组件中请求数据并推入相应的数组对象中, 会出现无法触发子组件计算属性的情况

问题出现的环境背景及自己尝试过哪些方法

  1. 创建三级分类的时候无法触发computed, watch无法监听到,试着用JSON.parase(JSON.stringify())深度拷贝,创建三级分类,computed时可以触发,四级分类可以创建,切换打开其他的一级分类,二级,三级都可以正常展开,四级分类可以加载到,但是无法触发Computed;watch也无法监听到

相关代码

// 请把代码文本粘贴到下方(请勿用图片代替代码)
子组件:

computed: {
    // 格式化数据源
    formatData: function () {
      let tmp
      if (!Array.isArray(this.data)) {
        tmp = [this.data]
      } else {
        tmp = this.data
      }
      const func = this.evalFunc || treeToArray
      const args = this.evalArgs ? Array.concat([tmp, this.expandAll], this.evalArgs) : [tmp, this.expandAll]
      return func.apply(null, args)
    }
  },
watch: {
    'data': {
      handler: function (newValue, oldValue) {
        console.log(newValue)
      },
      deep: true
    }
  },
methods: {
    // 切换下级是否展开
    toggleExpanded: function (trIndex, row) {
      if (row.children === undefined || row.children.length === 0) { // 是否异步请求数据
        this.$emit('tree-load', row)
        this.timer = setInterval(() => {
          if (this.isLoading) {
            const record = this.formatData[trIndex]
            record._expanded = !record._expanded
            clearInterval(this.timer)
          }
        }, 100)
      } else {
        const record = this.formatData[trIndex]
        record._expanded = !record._expanded
      }
      // this.selectedId = trIndex
    },
}

父组件:

methods: {
    onTreeLoad (row) {
      this.isLoading = false
      this.getSubClassifyList(row)
    },
    getSubClassifyList (params) {
      this.httpGet(apiUrl.category + params.code).then(res => {
        if (res.code === 0) {
          if (res.data) {
            // console.log(this.classifyList)
            this.insertArray(this.classifyList, res.data, params.code)
            // console.log(this.classifyList)
            this.classifyList = JSON.parse(JSON.stringify(this.classifyList))
          }
        }
        this.errorMessage(res)
      }).catch((err) => {
        this.errorCode(err)
      })
    },
    insertArray (Array, data, code) {
      let arr = Array
      for (let i = 0; i < arr.length; i++) {
        if (arr[i].children && arr[i].children.length > 0) {
          this.insertArray(arr[i].children, data, code)
        } else {
          if (arr[i].code === code) {
            arr[i]['children'] = JSON.parse(JSON.stringify(data))
            this.$set(arr, i, arr[i])
            this.isLoading = true
          }
        }
      }
    }
}

你期待的结果是什么?实际看到的错误信息又是什么?

1. 现在可以创建正常的四级分类,
阅读 3.1k
1 个回答
新手上路,请多包涵
  1. 该问题已解决, 解决思路是, 将所有的数据在父组件处理完成之后再传递给子组件.(子组件接收已处理好的数据)
    该思路已验证可行
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题