Vuejs는 이것을 타이프로 표현한다.$refs..값이 존재 하지 않음
내 VueJs 프로젝트를 타이프스크립트로 다시 쓰는 동안, 나는 TypeScript 오류를 발견했다.
이것은 사용자 지정 v-모델이 있는 구성 요소의 일부분이다.
html의 입력 필드에는 'plate'라는 ref가 있는데 나는 그 값에 접근하고 싶다.저 필드의 @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>
다음 작업을 수행하십시오.
class YourComponent extends Vue {
$refs!: {
checkboxElement: HTMLFormElement
}
someMethod () {
this.$refs.checkboxElement.checked
}
}
이번 호부터: https://github.com/vuejs/vue-class-component/issues/94
편집 - 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
}
오리지널
위의 답변들 중 내가 하고자 하는 것은 아무 것도 효과가 없었다.다음과 같은 $ref의 재산을 추가하면 결국 그것을 고치고 기대되는 재산을 회복하는 것 같았다.나는 이 Github 포스트에 연결된 해결책을 찾았다.
class YourComponent extends Vue {
$refs!: {
vue: Vue,
element: HTMLInputElement,
vues: Vue[],
elements: HTMLInputElement[]
}
someMethod () {
this.$refs.<element>.<attribute>
}
}
이것은 나에게 효과가 있다: 사용(this.$refs.<refField> as any).value
또는(this.$refs.['refField'] as any).value
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();
브래킷을 사용하지 마십시오.< >
그것은 JSX와 충돌할 것이기 때문에 타이프캐스트를 한다.
대신 이것을 사용해 보십시오.
update() {
const plateElement = this.$refs.plate as HTMLInputElement
this.$emit('input', { plate: plateElement.value });
}
내가 항상 기억하고 있는 노트로서
타이프스크립트는 타입의 안전을 보장하는 강력한 타이핑 기능을 가진 Javascript일 뿐이다.따라서 X(var, parameter 등)의 유형을 예측하지 않고 자동으로 어떤 연산도 입력하지 않는다.
또한, 활자체의 또 다른 목적은 JS코드를 더 선명하게/읽을 수 있게 만드는 것이므로, 가능한 경우 언제나 활자를 정의한다.
어쩌면 누군가에게 유용할지도 모른다.그것은 더 아름다워 보이고 여전히 활자 지지대로 남아 있다.
HTML:
<input ref="inputComment" v-model="inputComment">
TS:
const inputValue = ((this.$refs.inputComment as Vue).$el as HTMLInputElement).value;
사용자 정의 구성 요소 메서드를 호출할 경우,
그 요소 이름을 타이프로 방송할 수 있어서 그 방법을 쉽게 참고할 수 있어.
예)
(this.$refs.annotator as AnnotatorComponent).saveObjects();
여기서 AnnotatorComponent는 다음과 같은 클래스 기반 vue 구성 요소다.
@Component
export default class AnnotatorComponent extends Vue {
public saveObjects() {
// Custom code
}
}
나는 그것을 작동시킬 방법을 찾았지만 내 생각에는 추하다.
얼마든지 다른/더 나은 제안을 하십시오.
update() {
this.$emit('input', {
plate: (<any>this.$refs.plate).value,
});
}
다음을 통해 내보내기를 마무리하십시오.Vue.extend()
기존 파일을 변환하는 경우vue
js에서 ts로 투영하고 옛 형식을 유지하기를 원한다.
이전:
<script lang="ts">
export default {
mounted() {
let element = this.$refs.graph;
...
다음 이후:
<script lang="ts">
import Vue from "vue";
export default Vue.extend({
mounted() {
let element = this.$refs.graph;
...
Vue 3와 Options API를 사용하면 다음과 같은 효과를 얻을 수 있었다.
<script lang="ts">
import {defineComponent} from 'vue';
export default defineComponent({
methods: {
someAction() {
(this.$refs.foo as HTMLInputElement).value = 'abc';
},
},
});
</script>
자동완성은 그 결과를 가져오지 않는다.foo
로부터의 재산.$refs
템플릿에 정의되어 있고, 그것으로부터 유추된 정보는 없는 것 같으니까.
그러나 일단 캐스팅을 강행하면..foo
HTML 요소 유형에는 모든 것이 작동하므로 모든 요소 속성에 액세스할 수 있음)에 액세스할 수 있음.value
,의 예에에에.
'programing' 카테고리의 다른 글
왜 정적으로 연결된 glibc가 낙담하는가? (0) | 2022.04.23 |
---|---|
값 쌍의 Java 컬렉션?(튜플이요?) (0) | 2022.04.23 |
최대 절전 모드 사용 시 매개 변수 값으로 쿼리 문자열을 인쇄하는 방법 (0) | 2022.04.23 |
작성 및 읽기 작업에 동일한 양식을 사용 (0) | 2022.04.23 |
클래스 이름을 사용하여 인스턴스 생성 및 생성자 호출 (0) | 2022.04.23 |