首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Vuejs类型记录this.$refs.<refField>.value不存在

Vuejs类型记录this.$refs.<refField>.value不存在
EN

Stack Overflow用户
提问于 2017-09-30 18:28:03
回答 9查看 72.7K关注 0票数 54

在用类型记录重写VueJs项目时,我遇到了一个typescript错误。

这是具有自定义v模型的组件的一部分。

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

打字本在抱怨版面上不存在价值。

代码语言:javascript
运行
复制
@Prop() value: any;

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

模板:

代码语言:javascript
运行
复制
<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>
EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2018-03-17 03:08:50

你可以这样做:

代码语言:javascript
运行
复制
class YourComponent extends Vue {
  $refs!: {
    checkboxElement: HTMLFormElement
  }

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

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

票数 51
EN

Stack Overflow用户

发布于 2019-05-28 17:55:27

编辑- 2021-03 (合成API)

更新这个答案是因为Vue 3(或者如果您使用Vue 2的话是复合API插件)有一些新的功能。

代码语言:javascript
运行
复制
<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:

我推荐的图书馆提供@Ref,而不是我最初的答案。

代码语言:javascript
运行
复制
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哨所。上链接的解决方案

代码语言:javascript
运行
复制
class YourComponent extends Vue {
  $refs!: {
    vue: Vue,
    element: HTMLInputElement,
    vues: Vue[],
    elements: HTMLInputElement[]
  }

  someMethod () {
    this.$refs.<element>.<attribute>
  }
}
票数 45
EN

Stack Overflow用户

发布于 2021-01-15 02:11:46

son.vue

代码语言:javascript
运行
复制
const Son = Vue.extend({
  components: {},
  props: {},
  methods: {
    help(){}
  }
  ...
})
export type SonRef = InstanceType<typeof Son>;
export default Son;

parent.vue

代码语言:javascript
运行
复制
<son ref="son" />

computed: {
  son(): SonRef {
    return this.$refs.son as SonRef;
  }
}

//use
this.son.help();
票数 13
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46505813

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档