Switching from Vue's Options API to Composition API is like transforming your code from

My goal is to transition the code below from using the options API to the composition API in Vue while utilizing Typescript.

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)
    }
  }

This is my current implementation. As a newcomer to Vue and Typescript, I am using this example as a learning opportunity to delve deeper into the composition API along with 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,
    };
  },

The issues I'm encountering include errors such as in the setActiveItem method where it states that

'this' implicitly has type 'any' because it does not have a type annotation.
I have tried adding this: any parameters which seems to work, but I am unsure if this is the correct approach. Another challenge is getting the computed method to function properly. I am struggling to implement it correctly. If anyone can provide assistance on these matters, I would greatly appreciate it.

Answer №1

The primary aim of the composition API is to eliminate the usage of dynamic this which is not tied to a particular class instance, but rather an object that combines properties from component definition and imposes restrictions on TypeScript typing.

Instead, variables declared within the scope of setup should be directly accessed:

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

activeItem should also be a ref.

Answer №2

Here is a code snippet where you are importing the computed method by using

import { ref, computed } from "@vue/reactivity";
. Remember to access the value of a ref, you must use the value property. (The code below does not include typescript)

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,
};
},

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can videos be loaded in the front end through JavaScript when dragged and dropped?

I'm working on a project to create a web application that allows users to drag and drop a video file into the browser for processing using TensorFlow.js to make predictions. So far, I've accomplished the following: Loading the video file and p ...

How can we ensure that the load more button disappears at the appropriate moment in this Vue 3 application?

I have been developing a news application with Vue 3 and the News API. I am currently implementing a feature for loading more articles on the page. Initially, there are 24 articles displayed, and if there are more articles available than the current numbe ...

Is there a way to integrate Prettify with Blogger/BlogSpot?

I am currently utilizing blogger.com as a platform to showcase programming texts and I am interested in incorporating Prettify (similar to Stack Overflow) to enhance the appearance of my code samples. What is the best method for installing the Prettify sc ...

What are the steps to address the Invalid Hook Call issue while working with Material UI?

Having an issue with a MaterialUI Icon in my code as a newcomer to coding. Here is the snippet: import PersonIcon from '@mui/icons-material/Person'; function Header() { return ( <div> <PersonIcon /> <h2>Header file</h2 ...

Seamlessly incorporate Sass into your Vue-loader webpack setup

I am relatively new to this stack and currently in the process of learning how to use webpack with Vue. To kickstart my learning, I decided to download a bootstrap example application. However, I encountered an issue when trying to integrate Sass into the ...

Using jQuery to alter an href link's attribute

I am currently attempting to modify the content of a href using jQuery. After researching various solutions on this platform, I came across one that I am trying to use for implementation: How to change the href for a hyperlink using jQuery My current app ...

What is the best way to generate a random string output from an object in JavaScript?

I'm struggling with extracting a random value from the object provided below, can anyone help me out? const hellos = { English: "Hello", Japanese: "Konnichiwa", German: "Hallo", Spanish: "Hola", Arabic: "Ah ...

Please confirm the modal by adding a textarea with a newline in SweetAlert2

Every time I attempt to add a line break in the textarea input field, the modal pops up. I have tried adding these lines of code as well, but nothing seems to be working: allowEnterKey: false, focusConfirm: false, Does anyone have any advice for solving ...

Executing AJAX POST request with callback function

I successfully used this code for the get function to retrieve data. It works flawlessly and I am able to fetch the required data using this function. function getdata(getdatafrom, resultclass){ $.get(getdatafrom, function(data) { $(result ...

Is there a way to integrate Javascript code with a React component?

I need to find a way to include this block of code in just one specific React component. Any suggestions? <!-- Create a button that your customers click to complete their purchase. Customize the styling to suit your branding. --> <button sty ...

Is it advisable to incorporate both Jquery and AngularJs into progressive web applications?

Currently, I am in the process of constructing a progressive test application. So far, all the tutorials I have come across utilize native JavaScript. My inquiry is whether it is possible to leverage Jquery for streamlined code writing and implement an MVC ...

Tips for enhancing a search algorithm

I am currently working on implementing 4 dropdown multi-select filters in a row. My goal is to render these filters and update a new array with every selected option. Additionally, I need to toggle the 'selected' property in the current array of ...

React Quill editor fails to render properly in React project

In the process of developing an application in Ionic React, I am in need of a rich text editor that can save data on Firestore. Despite initializing the editor as shown below and adding it to the homepage component, it is not rendering correctly although i ...

Ensure that the context is used to effectively clear any existing data from the previous bar chart

I recently came across a cool codepen demo on this link. Upon clicking the first button followed by the second, the data transitions smoothly. However, there seems to be an issue where when hovering randomly over the bar charts at this source, the value ...

Troubleshooting: Issues with Ajax loading page and click functionality in jQuery

Why won't my ajax function properly? Here are the details of my pages. I am using JQuery to monitor click events and implement ajax for loading the responder page. Can you spot any issues in this code snippet? index.php <html> <head ...

Difficulty arises when collapsed text in Bootstrap clashes with the footer design

Hey there! I'm working on this website using Bootstrap, and I've encountered a problem. When you click the "See Wikipedia" button, the content expands and overlaps the footer in a strange way without changing the page height. I've tried adju ...

Eliminate list items with a keyboard stroke

I am currently developing a straightforward todo list application using JavaScript. The main functionality I am trying to implement is the ability to add new items from an input field to a list, as well as the option to remove items from the list. While ...

encountered empty values when retrieving static paths

I need to retrieve the values of slug and tags in my params. It's important to note that tags is not an array, but just a string. export async function getStaticPaths() { const chapters = await client.fetch( `*[_type == "chapters" & ...

bind a class property dynamically in real-time

I need to dynamically generate a TypeScript class and then add a property to it on the go. The property could be of any type like a function, Promise, etc., and should use this with the intention that it refers to the class itself. let MyClass = class{ ...

Creating a real-time clock in a single line console log format using NodeJS

To create a live clock in a single line display within a browser, we can utilize setInterval and manipulate the content inside an HTML element like so: var span = document.getElementById('span'); function time() { var d = new Date ...