Vuejs typescript this.$refs.<refField>.value does not exist

只谈情不闲聊 提交于 2020-02-21 09:48:29

问题


While rewriting my VueJs project in typescript, I came across a TypeScript error.

This is a part of the component that has a custom v-model.

An input field in the html has a ref called 'plate' and I want to access the value of that. The @input on that field calls the update method written below.

Typescript is complaining that value does not exist on plate.

@Prop() value: any;

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

template:

<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>

回答1:


You can do this:

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

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

From this issue: https://github.com/vuejs/vue-class-component/issues/94




回答2:


This worked for me: use (this.$refs.<refField> as any).value or (this.$refs.['refField'] as any).value




回答3:


Avoid using bracket < > to typecast because it will conflict with JSX.

Try this instead

update() {
    const plateElement = this.$refs.plate as HTMLInputElement
    this.$emit('input', { plate: plateElement.value });
}

as a note that I always keep remembering

Typescript is just Javascript with strong typing capability to ensure type safety. So (usually) it doesn't predict the type of X (var, param, etc) neither automatically typecasted any operation.

Also, another purpose of the typescript is to make JS code became clearer/readable, so always define the type whenever is possible.




回答4:


None of the above answers worked for what I was trying to do. Adding the following $refs property wound up fixing it and seemed to restore the expected properties. I found the solution linked on this github post.

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

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



回答5:


Maybe it will be useful to someone. It looks more beautiful and remains type support.

HTML:

<input ref="inputComment" v-model="inputComment">

TS:

const inputValue = ((this.$refs.inputComment as Vue).$el as HTMLInputElement).value;



回答6:


I found a way to make it work but it is ugly in my opinion.

Feel free to give other/better suggestions.

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


来源:https://stackoverflow.com/questions/46505813/vuejs-typescript-this-refs-reffield-value-does-not-exist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!