我只是想在我的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>

removeProduct函数中的第this.$refs.multi.deselect(product)行是产生错误的那一行.

以下是通过文档指示使用的方式:

mounted() {
  this.$refs.multiselect.open()
}

推荐答案

Boussadjra Brahim所说的是有效的,但不推荐使用,因为看起来所有东西都在使用products数组,为什么不直接删除要取消 Select 的项目(删除?)从中,它应该同时更新您的多选项和显示列表.

<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()人做了什么

Vue.js相关问答推荐

Vuetify从同一方向旋转传送带下一个项目和上一个项目

在预渲染模式下部署 nuxt 3 时出错

将 v-calendar 与以时间和日期格式出现的事件一起使用

VSelect - Select 不适用于 Vuetify 3 中的自定义项目插槽

在 VueJS 中为 Get、Post、Patch 配置全局标头的最佳方法

JSDoc 单文件 Vue 组件

云Firestore保存额外的用户数据

aspnet core如何在deploy上构建webpack

Eslint Vue 3 解析错误:'>' expected.eslint

使用数组元素的计算(computed)属性

未捕获的错误:[vue-composition-api] 必须在使用任何函数之前调用 Vue.use(plugin)

在 vue 组件中检索配置和环境变量

Vue @click 不适用于存在 href 的anchor锚标记

Vuejs 2,VUEX,编辑数据时的数据绑定

我可以使用 vue.js v-if 来判断值是否存在于数组中

vuejs中通过变量动态调用方法

Vuejs模板继承

加载时焦点文本框上的 Vue.js

输入文件 Select 事件在 Select 同一文件时未触发

了解 Nuxt.js 中的State状态和Getters:Getters不起作用