【问题标题】:Vue cannot get refs on mounted on nextTick after dynamically importing the component?动态导入组件后,Vue 无法在 nextTick 上获取 refs?
【发布时间】:2022-01-12 17:45:06
【问题描述】:

我正在使用 Nuxt js 和 Element UI。我在插件文件夹中动态导入了元素 UI 插件。

export default () => {
  Vue.component("ElForm", () => import("element-ui/lib/form"));
  Vue.component("ElFormItem", () => import("element-ui/lib/form-item"));
  Vue.component("ElInput", () => import("element-ui/lib/input"));
  ......
}

现在,当我打开一个包含组件的模式对话框时。它返回参考错误。这可能是因为组件尚未加载。我该如何处理这种情况?即使nextTick 也不起作用。

<template>
  <div>
    <el-form
      :model="form"
      :rules="rules"
      ref="ruleForm"
      v-loading="loading"
      @submit.prevent.native="submitOnReturn"
    >
      <el-form-item label="Title" prop="title">
        <el-input v-model="form.title" ref="inputField" :autofocus="true" />
      </el-form-item>
      <el-form-item label="Details" prop="body">
        <el-input v-model="form.body" type="textarea" :rows="4" />
      </el-form-item>
      <el-form-item class="form-buttons">
        <el-button type="" @click="cancel">Cancel</el-button>
        <el-button type="primary" @click="updateProductFaq" v-if="editMode"
          >Update</el-button
        >
        <el-button type="primary" @click="addProductFaq" v-else>Save</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
  mounted() {
    this.$nextTick(() => {
      // focus input on mount
      this.$refs.inputField.focus();
      this.$refs.ruleForm.clearValidate();
    });
  },

this.$refs.inputField 未定义

【问题讨论】:

    标签: javascript vue.js vue-component nuxt.js


    【解决方案1】:

    el-input 的模板引用在包含组件的 mounted 挂钩中不可用,因为输入是异步呈现的。

    一种解决方法是为el-inputhook:mounted 事件添加一个处理程序(与组件的mounted 挂钩发生),其中模板引用将被填充:

    <el-input ref="inputField" @hook:mounted="$refs.inputField.focus()" />
                                       ?
    

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-03-29
      • 2018-07-05
      • 2019-04-23
      • 2020-06-18
      • 2019-02-03
      • 2020-01-24
      • 2021-11-16
      • 2020-02-25
      相关资源
      最近更新 更多