我只是想在我的 Vue 3 应用程序中使用 $refs
,但我一直收到 Typescript 错误 Object is of type 'unknown'
。我不知道如何解决这个问题。
这是我的 .vue 文件:
<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>
this.$refs.multi.deselect(product)
函数中的 removeProduct
行是产生错误的那一行。
这是通过文档指示使用它的方式:
mounted() {
this.$refs.multiselect.open()
}
答案 0 :(得分:1)
Boussadjra Brahim 所说的有效,但不建议这样做,因为看起来一切都在使用 products
数组,为什么不简单地删除要取消选择的项目(删除 ? ),它应该同时更新您的 MultiSelect 和显示列表。
<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);
},
},
我不确定它是否正确,我有点缺乏上下文来确定它,比如 deselect()
是做什么的
答案 1 :(得分:0)
可能是您的 element hasn't been rendered yet。
您可以尝试在访问 $refs
之前稍微延迟一下吗?
mounted(){
setTimeout(() => {
this.$refs.multiselect.open()
}, 10)
},