Vuejs 打字稿 this.$refs.<refField>.value 不存在

新手上路,请多包涵

在使用 typescript 重写我的 VueJs 项目时,我遇到了一个 TypeScript 错误。

这是具有自定义 v-model 的组件的一部分。

html 中的输入字段有一个名为“plate”的引用,我想访问它的值。该字段上的@input 调用下面编写的更新方法。

打字稿抱怨盘子上不存在价值。

 @Prop() value: any;

update() {
    this.$emit('input',
        plate: this.$refs.plate.value
    });
}

模板:

 <template>
<div>
    <div class="form-group">
        <label for="inputPlate" class="col-sm-2 control-label">Plate</label>

        <div class="col-sm-10">
            <input type="text" class="form-control" id="inputPlate" ref="plate" :value="value.plate" @input="update">
        </div>
    </div>

</div>
</template>

原文由 Rick 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 380
2 个回答

你可以这样做:

 class YourComponent extends Vue {
  $refs!: {
    checkboxElement: HTMLFormElement
  }

  someMethod () {
    this.$refs.checkboxElement.checked
  }
}

从这个问题: https ://github.com/vuejs/vue-class-component/issues/94

原文由 George 发布,翻译遵循 CC BY-SA 4.0 许可协议

编辑 - 2021-03(组合 API)

更新这个答案是因为 Vue 3(如果您使用的是 Vue 2,则为组合 API 插件)具有一些新功能。

 <template>
  <div ref="root">This is a root element</div>
</template>

<script lang="ts">
  import { ref, onMounted, defineComponent } from '@vue/composition-api'

  export default defineComponent({
    setup() {
      const root = ref(null)

      onMounted(() => {
        // the DOM element will be assigned to the ref after initial render
        console.log(root.value) // <div>This is a root element</div>
      })

      return {
        root
      }
    }
  })
</script>

编辑 - 2020-04:

vue-property-decorator 库提供了我推荐的@Ref ,而不是我原来的答案。

 import { Vue, Component, Ref } from 'vue-property-decorator'

import AnotherComponent from '@/path/to/another-component.vue'

@Component
export default class YourComponent extends Vue {
  @Ref() readonly anotherComponent!: AnotherComponent
  @Ref('aButton') readonly button!: HTMLButtonElement
}


原始答案

以上答案都不适用于我想做的事情。添加以下 $refs 属性最终修复了它,并且似乎恢复了预期的属性。我在 这个 github 帖子上找到了链接的解决方案。

 class YourComponent extends Vue {
  $refs!: {
    vue: Vue,
    element: HTMLInputElement,
    vues: Vue[],
    elements: HTMLInputElement[]
  }

  someMethod () {
    this.$refs.<element>.<attribute>
  }
}

原文由 John Snow 发布,翻译遵循 CC BY-SA 4.0 许可协议

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