Vue 递归组件getElementyById获取问题

我是Vue初学者,写了一个树组件,在用ID获取组件的时候出现了一些问题。getElementById总是返回null
先贴出代码

这是函数代码
methods: {
    drawLine: function(node) {
      console.log(node.id + " " + document.getElementById(node.id))
    }
  },
这是nextTick里面的代码
mounted() {
    this.$nextTick(() => {
      this.domready = true
      this.drawLine(this.root)
    })
  },
这是结果
写在蓝色方框前面的是id,后面的是组件

总之就是发现只有最后的节点可以获取到
其他的节点都获取不到
提前谢谢大家了

全部代码
SideTree.vue

<template>
  <div class="side_tree" :style="(side === 'left') ? {marginRight: '30px'} : {marginLeft: '30px'}" v-if="this.domready">
    <div class="frame" style="display: inline-block">
      {{root.id}}
      <tag :content="root.title"></tag>
    </div>
    <div style="display: inline-block">
      <div v-for="(child , index) in root.children"
           :key="root.id + '-child-' + index"
           :id="child.id"

      v-if="root.children.length !== 0"
      :style="(index === 0) ? {} : {marginTop: '30px'}">
      <Side-tree :root="child" :side="side"></Side-tree>
      </div>
    </div>
  </div>
</template>

<script>
//import LeaderLine from 'leader-line-vue'
import tag from './Tag'
export default {
  name: "SideTree",
  props: ['root' , 'side'],
  data() {
    return {
      line: [],
      domready: false
    }
  },
  created() {
  },
  mounted() {
    this.$nextTick(() => {
      this.domready = true
      this.drawLine(this.root)
    })
  },
  methods: {
    drawLine: function(node) {
      console.log(node.id + " " + document.getElementById(node.id))
    }
  },
  components: {
    tag
  }
}
</script>

<style scoped>
.frame:before
{
  content: " ";
  height: 100%;
  vertical-align: middle;
  display: inline-block;
}
</style>

Tag.vue

<template>
  <span class="tag" :style="{backgroundColor: color}">
    {{title}}
  </span>
</template>

<script>
export default {
  name: "Tag",
  props: ['content' , 'status'],
  data() {
    return {
      title: null,
      color: '#409EFF',
      check: false
    }
  },
  watch: {
    status() {
      if(this.status) this.color = '#E6A23C'
      else this.color = '#409EFF'
    },
  },
  created() {
    if(this.content) this.title = this.content
  }
}
</script>

<style scoped>
.tag
{
  font-size: 1em;
  color: whitesmoke;
  border-radius: 7px;
  border: 1px solid #8fa4ff;
  padding: 5px 10px 5px 10px;
}
</style>
阅读 2.2k
1 个回答
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题