You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Vue中如何通过ref获取元素用于Shepherd引导组件?

解决Vue父组件获取ref元素为null的问题

问题原因

在beforeMount钩子执行时,组件的DOM还未完成渲染,此时$refs.button对应的DOM元素还不存在,所以会返回null。

正确解决方案

1. 调整父组件获取ref的时机

将获取ref的逻辑放到mounted钩子中,并配合$nextTick确保DOM完全渲染完成:

mounted() {
  this.$nextTick(() => {
    this.element = this.$refs.button;
  });
}

mounted钩子触发时,组件的DOM已经挂载完成;$nextTick则会在DOM更新循环结束后执行回调,进一步保证目标元素已经存在。

2. 给Guide组件增加空值判断

为了避免传递的元素为null导致Shepherd初始化报错,在Guide组件的mounted钩子中先判断元素是否存在,再执行初始化逻辑:

mounted() {
  this.$nextTick(() => {
    if (this.element) {
      const tour = this.$shepherd({
        defaultStepOptions: {
          cancelIcon: { enabled: true },
          classes: 'class-1 class-2',
          scrollTo: { behavior: 'smooth', block: 'center' },
        },
      });

      tour.addStep({
        attachTo: { element: this.element, on: this.position },
        title: this.title,
        text: this.text,
        buttons: [
          {
            action() { return this.back(); },
            classes: 'shepherd-button-secondary',
            text: 'Back',
          },
          {
            action() { return this.next(); },
            text: 'Next',
          },
        ],
        id: 'creating',
      });

      tour.start();
    }
  });
}

3. 额外说明

如果父组件中的按钮是通过条件渲染(比如v-if)显示的,还需要确保在按钮渲染完成后再传递元素。可以通过watch监听控制按钮显示的变量,在变量为真时再执行获取ref的操作。

内容的提问来源于stack exchange,提问作者World's famous people

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 09:26:15