【问题标题】:Vue: Convert code from Options to Composition APIVue:将代码从选项转换为组合 API
【发布时间】:2021-10-29 03:55:12
【问题描述】:

我正在尝试使用 Typescript 将以下代码表单选项转换为 Vue 中的组合 API。

data() {
    return {
      items: [
        'Car',
        'Truck',
        'Bike',
        'Caravan'
      ],
      activeItem: 0,
      show: false,
    };
  },
  methods: {
    showDropdown() {
      this.show = !this.show;
    },
    setActiveItem(item) {
      this.activeItem = this.items.indexOf(item);
      this.show = false;
    }
  },
  computed: {
    dropdownItems() {
      return this.items.filter((item,i) => i !== this.activeItem)
    }
  }

这就是我所拥有的。我还是 Vue 和 Typescript 的新手,所以我使用这个例子来了解更多关于组合 API 和 Typescript 的信息。

setup() {
    const activeItem = 0;
    const show = ref(false);

    const items = ref([
        'Car',
        'Truck',
        'Bike',
        'Caravan'
    ]);

    function showDropdown(this: any) {
      this.show = !this.show;
    }

    function setActiveItem(this: any, item: string) {
      this.activeItem = this.items.indexOf(item);
      this.show = false;
    }

    const dropdownItems = computed(function (this: any, item: string) {
      return this.items.filter((item, i) => i !== this.activeItem);
    });

    return {
      activeItem,
      show,
      items,
      showDropdown,
      setActiveItem,
      dropdownItems,
    };
  },

我遇到的错误例如在setActiveItem 方法中是'this' implicitly has type 'any' because it does not have a type annotation. 所以当我通过this: any 参数时它可以工作,但我不知道这是否是正确的方法? 第二个问题是我无法让计算方法工作我不知道如何正确实现它。有人可以帮我解决这个问题吗?

【问题讨论】:

    标签: javascript vue.js vue-component vue-composition-api


    【解决方案1】:

    您只需导入import { ref, computed } from "@vue/reactivity"; 的计算方法。对于ref,您需要使用value。 (以下代码没有打字稿)

    import { ref, computed } from "@vue/reactivity";
    
    setup() {
    const activeItem = ref(0);
    const show = ref(false);
    const items = ref([
        'Car',
        'Truck',
        'Bike',
        'Caravan'
    ]);
    
    const dropdownItems = computed(() => items.value.filter((item, i) => i !== activeItem.value));
    
    const showDropdown = () => {
      show.value = !show.value;
    }
    
    const setActiveItem = (item) => {
      activeItem.value = items.value.indexOf(item);
      show.value = false;
    }
    
    return {
      activeItem,
      show,
      items,
      showDropdown,
      setActiveItem,
      dropdownItems,
    };
    },
    

    【讨论】:

      【解决方案2】:

      组合 API 的目标是摆脱动态 this,它不是特定类的实例,而是聚合来自组件定义的属性并限制 TypeScript 类型的对象。

      相反,setup 范围内定义的变量应该可以直接访问:

      const dropdownItems = computed((item: string)  => {
        return unref(items).filter((item, i) => i !== unref(activeItem));
      });
      

      activeItem 也应该是一个 ref。

      【讨论】:

        猜你喜欢
        • 2022-12-24
        • 1970-01-01
        • 2018-04-27
        • 2021-04-20
        • 2016-09-14
        • 2022-10-19
        • 2020-07-12
        • 2019-01-14
        • 1970-01-01
        相关资源
        最近更新 更多