I'm simply trying to use $refs
in my Vue 3 app but I keep getting the Typescript error Object is of type 'unknown'
. I'm not sure how to fix this.
Here's my .vue file:
<template>
<div id="content">
<h2>
Add Products
</h2>
<Multiselect v-model="products"
mode="tags"
placeholder="Select one or more products..."
ref="multi"
:searchable="true"
:createTag="true"
:options="options"></Multiselect>
<div v-for="(product, index) in this.products"
v-bind:key="index"
v-bind:name="product">
<Button class="primary"
text="Remove"
@click="removeProduct(product)"></Button>
</div>
</div>
</template>
<script lang="ts">
import { defineComponent } from 'vue'
import Button from '@/components/Button.vue'
import Multiselect from '@vueform/multiselect'
export default defineComponent({
name: 'TrackSymptoms',
components: {
Button,
Multiselect
},
data () {
return {
products: [],
options: [
{ value: 'Alpha', label: 'Alpha' },
{ value: 'Bravo', label: 'Bravo' },
{ value: 'Charlie', label: 'Charlie' },
{ value: 'Delta', label: 'Delta' }
]
}
},
methods: {
removeProduct (product: string) {
this.$refs.multi.deselect(product)
}
}
})
</script>
The line this.$refs.multi.deselect(product)
in the removeProduct
function is the one producing the error.
This is how it's instructed to be used via the docs:
mounted() {
this.$refs.multiselect.open()
}
<el-table
:data="tableData"
@row-click="rowClicked"
ref="tableRef"
>
rowClicked(row: any) {
(this.$refs['tableRef'] as any).toggleRowExpansion(row);
}
force the any type on the object
edit....better solution found by colleague. import relevant type available from search in node_module code of element-plus. In this case the el-table has a type:
import { ElTable } from 'element-plus';
(this.$refs['tableRef'] as typeof ElTable).toggleRowExpansion(row);
Define type for the component you assigned ref to, like below:
(this.$refs.multi as InstanceType<typeof Multiselect>).deselect(product)
This should be a better solution than the other answers (no offense).
(this.$refs['tableRef'] as any).toggleRowExpansion(row);
coz with my solution you can use IDE'S code completion.
what Boussadjra Brahim said, works but it's not recommended, instead, since it looks like everything is using the products
array, why don't you simply remove the item you want to deselect (remove ?) from it, it should update your MultiSelect and displayed list at the same time.
<div v-for="(product, index) in this.products" :key="index" :name="product">
<Button class="primary" text="Remove" @click="removeProduct(index)"></Button>
</div>
methods: {
/**
* Remove the product at the specified index
*/
removeProduct(index: number) {
this.products.splice(index, 1);
},
},
i'm not sure it's right though, i'm a bit lacking in context to be sure of it, like what does the deselect()
do
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With