在用类型记录重写VueJs项目时,我遇到了一个typescript错误。
这是具有自定义v模型的组件的一部分。
html中的输入字段有一个名为“plate”的ref,我希望访问该字段的值。该字段上的@输入调用下面编写的更新方法。
打字本在抱怨版面上不存在价值。
@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>
发布于 2018-03-17 03:08:50
你可以这样做:
class YourComponent extends Vue {
$refs!: {
checkboxElement: HTMLFormElement
}
someMethod () {
this.$refs.checkboxElement.checked
}
}
从这个问题:https://github.com/vuejs/vue-class-component/issues/94
发布于 2019-05-28 17:55:27
编辑- 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:
我推荐的图书馆提供@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>
}
}
发布于 2021-01-15 02:11:46
son.vue
const Son = Vue.extend({
components: {},
props: {},
methods: {
help(){}
}
...
})
export type SonRef = InstanceType<typeof Son>;
export default Son;
parent.vue
<son ref="son" />
computed: {
son(): SonRef {
return this.$refs.son as SonRef;
}
}
//use
this.son.help();
https://stackoverflow.com/questions/46505813
复制相似问题