vue3中为什么使用nextTick还是无法获取组件的ref值?

新手上路,请多包涵
<template>
  <el-card>
    <MySearch v-model="query" title="添加角色" @add="showDialog" />

    <PageContent
      ref="pageContentRef"
      :query="query"
      :content-table-config="contentTableConfig"
      page-name="role"
      @edit="handleEdit"
    />

    <MyDialog
      ref="myDialogRef"
      page-name="role"
      :form-config="formConfig"
      :default-info="defaultInfo"
      :permission-list="permissionList"
    >
      <el-tree
        ref="elTreeRef"
        :data="menuList"
        show-checkbox
        node-key="_id"
        :props="{ children: 'children', label: 'name' }"
        @check="handleChangeCheck"
      />
    </MyDialog>
  </el-card>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { useStore } from 'vuex'

import MySearch from '@/components/search/search.vue'
import PageContent from '@/components/page-content/page-content.vue'
import MyDialog from '@/components/dialog/dialog.vue'

import { contentTableConfig } from './config/table.config'
import { formConfig } from './config/form.config'
import { useSearch } from '@/hooks/use-search'
import { useDialog } from '@/hooks/use-dialog'

// hooks
const { query, pageContentRef } = useSearch()
const { myDialogRef, defaultInfo, showDialog, handleEdit } = useDialog(
  null,
  editFn
)

// data
const elTreeRef = ref()
const permissionList = ref({})

// vuex
const store = useStore()
const menuList = computed(() => store.state.entireMenu)

function handleChangeCheck(list, data) {
  const { checkedKeys, halfCheckedKeys } = data
  permissionList.value = { checkedKeys, halfCheckedKeys }
}

async function editFn(item) {
  // const checked = [
  //   ...item.permissionList.checkedKeys,
  //   ...item.permissionList.halfCheckedKeys
  // ]
  await nextTick()
  console.log(elTreeRef.value)
  // nextTick(() => {
  //   console.log(elTreeRef.value)
  //   // elTreeRef.value.setCheckedKeys(checked)
  // })
}
</script>

<style lang="scss" scoped></style>

想获取el-tree的ref调用setCheckedKeys设置节点,但一直获取elTreeRef的值一直为null

阅读 7k
2 个回答

因为你包在dialog里,dialog没有展示的时候是没有dom节点,也就是没有实例的。你把dialog展示出来再去获tree的ref,就能找到了

vue3中 ref是将值变为响应式对象。你初始化的时候没有传参,后面也没修改它,所以它一直是null。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题