Reputation: 1334
Template:
<template>
<div ref="element"></div>
</template>
Script:
export default {
setup() {
const element = ref(null);
return {
element,
};
},
};
This is a normal way to define a ref in vue3, but in JavaScript way.
And if I'm using TypeScript, I will need to define a type for value element
, right?
How do I do to ensure the correct type for value element
?
Upvotes: 69
Views: 118046
Reputation: 69
According the official docs: Typing ref(), use type Ref
in vue
Example:
import type { Ref } from 'vue'
name: Ref<string> = ref()
interface IUser {
name: string,
sex: string
}
user: Ref<IUser> = ref({
name: '',
sex: ''
})
Upvotes: 2
Reputation: 7307
From the Vue 3 docs:
Components using <script setup>
are closed by default - i.e. the public instance of the component, which is retrieved via template refs or $parent
chains, will not expose any of the bindings declared inside .
To explicitly expose properties in a component, use the defineExpose compiler macro:
<script setup>
import { ref } from 'vue'
const a = 1
const b = ref(2)
defineExpose({
a,
b
})
</script>
When a parent gets an instance of this component via template refs, the retrieved instance will be of the shape { a: number, b: number }
(refs are automatically unwrapped just like on normal instances).
Component MyModal.vue
:
<script setup lang="ts">
import { ref } from 'vue'
const isContentShown = ref(false)
const open = () => (isContentShown.value = true)
defineExpose({
open
})
</script>
Parent component App.vue
:
<script setup lang="ts">
import MyModal from './MyModal.vue'
const modal = ref<InstanceType<typeof MyModal> | null>(null)
const openModal = () => {
modal.value?.open()
}
</script>
Upvotes: 8
Reputation: 77
import { VNodeRef } from 'vue';
You can use VNodeRef.
const swiperRef = ref<VNodeRef>();
Upvotes: 5
Reputation: 4603
Vue 3 composition API
<template>
<input ref="fileInput" style="display: none;" type="file" @change="onFileSelected" />
<button @click="fileInput?.click()">Pick Files</button>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const fileInput = ref<HTMLDivElement | null>(null)
function onFileSelected(event: any) { console.log("Event: " + event) }
</script>
Second example
<template>
<div ref="coolDiv">Some text</div>
<button @click="changeCoolDiv">Pick Files</button>
</template>
<script setup lang="ts">
import { ref } from 'vue'
const coolDiv = ref<HTMLDivElement>()
function changeCoolDiv() {
if(coolDiv) {
coolDiv.value // Div element
}
}
</script>
Upvotes: 10
Reputation: 434
If using the vue-class-component
package (here the beta v8 but the same with @Component
instead of @Option
will work in earlier versions):
<template>
<div ref="element">
<MyOtherComponent ref="otherComponent" />
</div>
</template>
<script lang="ts">
import { Options, Vue } from 'vue-class-component'
import MyOtherComponent from '../MyOtherComponent.vue'
@Options({
components: {
MyOtherComponent,
},
})
export default class MyComponent extends Vue {
$refs!: {
element: HTMLDivElement,
otherComponent: InstanceType<typeof MyOtherComponent>,
}
mounted() {
this.$refs.otherComponent.myOtherComponentMethod()
}
}
</script>
Upvotes: 2
Reputation: 671
<template>
<ChildComponent ref="childRef">
</template>
<script lang="ts" setup>
import ChildComponent from './ChildComponent.vue'
import { ref } from 'vue'
const childRef = ref<InstanceType<typeof ChildComponent>>()
childRef.value.childMethods()
</script>
Upvotes: 67
Reputation: 2197
The line isn't correct:
const el = ref<HTMLDivElement>();
The el
is not an HTMLDivElement. Instead, it's a proxy to the element. The $el
of that proxy is the actual HTMLDivElement. Though I'm not sure if I get it right. In a component, I managed to type it as follow:
import { ComponentPublicInstance, defineComponent, ref } from 'vue';
export default defineComponent({
// snipped...
setup() {
const field = ref<ComponentPublicInstance<HTMLInputElement>>();
return {
field,
fun() { field.value.$el.value = 'some value'; }
};
}
// snipped...
});
Upvotes: 17
Reputation: 9180
Well, that would depend on whether or not you need it typed and to provide member information (public properties, methods, etc). If you do, then yes you need to define a type for it; otherwise, you don't have to, and can simply access the unwrapped reference with .value
which leaves it as type any
(I bet you figured out this one).
But if you have to, you need to tell the compiler what it is or what it's going to be assigned on. To do that, you'll want to use the third overload of ref
(with no argument) and explicitly set the generic type to the desired type—in your case, you want HTMLDivElement
(or simply HTMLElement
if you don't care about the specific members it has to offer).
export default defineComponent({
setup() {
const el = ref<HTMLDivElement>();
onMounted(() => {
el.value // DIV element
});
return {
el
}
}
})
In JavaScript, you don't have type checking, so passing null
on the ref
function is as good as not passing anything (which is especially okay for template refs)*; it could even come across as being misleading in a sense that the unwrapped value actually resolves to something else but null
.
* When using the Composition API, the concept of "reactive refs" and "template refs" are unified. And the reason we're accessing this particular type of ref
on the mounted hook is because the DOM element will be assigned to it after initial render.
References:
Upvotes: 44