Vuejs typescript this.$refs..value does not exist

前端 未结 7 1448
野的像风
野的像风 2020-11-30 13:33

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 i

相关标签:
7条回答
  • 2020-11-30 14:00

    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,
        });
    }
    
    0 讨论(0)
  • 2020-11-30 14:03

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

    0 讨论(0)
  • 2020-11-30 14:04

    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

    0 讨论(0)
  • 2020-11-30 14:07

    Edit - 2020-04:

    The vue-property-decorator library provides @Ref which I recommend instead of my original answer.

    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
    }
    

    Original Answer

    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>
      }
    }
    
    0 讨论(0)
  • 2020-11-30 14:08

    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;
    
    0 讨论(0)
  • 2020-11-30 14:08

    In case of custom component method call,

    we can typecast that component name, so it's easy to refer to that method.

    e.g.

    (this.$refs.annotator as AnnotatorComponent).saveObjects();
    

    where AnnotatorComponent is class based vue component as below.

    @Component
    export default class AnnotatorComponent extends Vue {
        public saveObjects() {
            // Custom code
        }
    }
    
    0 讨论(0)
提交回复
热议问题