Joe*_*lot 9 typescript vue.js vue-component vuejs3
我只是想$refs在我的 Vue 3 应用程序中使用,但我一直收到 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>
Run Code Online (Sandbox Code Playgroud)
线this.$refs.multi.deselect(product)在removeProduct函数是一个生产误差。
这是通过文档指示使用它的方式:
mounted() {
this.$refs.multiselect.open()
}
Run Code Online (Sandbox Code Playgroud)
Sup*_*Ted 14
<el-table
:data="tableData"
@row-click="rowClicked"
ref="tableRef"
>
rowClicked(row: any) {
(this.$refs['tableRef'] as any).toggleRowExpansion(row);
}
Run Code Online (Sandbox Code Playgroud)
强制对象使用任何类型
编辑...同事找到了更好的解决方案。导入可在element-plus的node_module代码中搜索到的相关类型。在本例中,el-table 的类型为:
import { ElTable } from 'element-plus';
(this.$refs['tableRef'] as typeof ElTable).toggleRowExpansion(row);
Run Code Online (Sandbox Code Playgroud)
为您分配 ref 的组件定义类型,如下所示:
(this.$refs.multi as InstanceType<typeof Multiselect>).deselect(product)
Run Code Online (Sandbox Code Playgroud)
这应该是比其他答案更好的解决方案(无意冒犯)。
(this.$refs['tableRef'] as any).toggleRowExpansion(row);
Run Code Online (Sandbox Code Playgroud)
因为通过我的解决方案,您可以使用 IDE 的代码完成功能。
小智 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>
Run Code Online (Sandbox Code Playgroud)
methods: {
/**
* Remove the product at the specified index
*/
removeProduct(index: number) {
this.products.splice(index, 1);
},
},
Run Code Online (Sandbox Code Playgroud)
我不确定这是正确的,我有点缺乏上下文来确定它,比如它是做什么deselect()的
| 归档时间: |
|
| 查看次数: |
1639 次 |
| 最近记录: |