executing a function within a Vue.js 3 component's <template> tag

As I delved into the world of fetching APIs and displaying their data on a Vue.js3 webpage, I encountered an interesting issue. My goal was to showcase different dog breeds and have a random dog image display when a breed is clicked. However, when I tried calling the function fetchAPI(), I ran into this error: https://i.sstatic.net/39RKO.png

Curiously, assigning the function to a variable fun and then calling that variable resolved the problem and made it work perfectly. But why did that make a difference? Below is the snippet of code causing me all this confusion:

<template>

  <div class="dog"> 
    <ul class="dog__ul">
        <li class="dog__li" v-for="(value, name) in data.message" :key="name"
            @click="fun"
              //When using `fetchAPI()` instead of "fun", it throws an error
          >
          {{ name }} 
        </li>
    </ul>
    <img :src="image" alt="dog picture" class="dog__img"> 
  </div> 
</template> 
  
<script>
import { ref , onMounted, onUnmounted } from 'vue';

export default { 

setup(){
  const data = ref({});
  let image = ref(null);
  
  let fun = fetchAPI;
  function fetchList(){ 
      fetch("https://dog.ceo/api/breeds/list/all")
        .then(response => response.json()) 
        .then(info=>data.value = info)
        .catch(err => console.log (err.message))
  }
  
  function fetchAPI(){ 
      fetch(`https://dog.ceo/api/breeds/image/random`)
        .then(response => response.json()) 
        .then(val=>image.value = val.message)
        .catch(err => console.log (err.message))
  }

  onMounted(() => {
    console.log ("Mount : DogAPI  Mounted ⭕");
    fetchAPI();
    fetchList(); 
  });
  
  onUnmounted(() => console.log("unMount: DogAPI Unounted ❌ "));
    
  return {
    data,
    image,
    fun,
  };
}
}; 
</script>

Answer №1

To access a variable or function in the template, it must be explicitly returned from the setup() function.

Therefore, you will have to modify your code as follows:

return {
  info,
  picture,
  action,
  callAPI
}

Only then will it behave according to your expectations.

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

Tailwind CSS not applying styles to my Next.js project on Ubuntu operating system

I'm experiencing a strange issue where Tailwind CSS is not applying any styles to my project on Ubuntu 20.04. Interestingly, the project works perfectly fine on Windows but for some reason, it's not styling at all on Ubuntu. https://i.sstatic.n ...

Press the submit button after receiving the ajax response

Is there a way to manually or programmatically submit a specific page? The catch is that before the submission can happen, a function called create_impi_num(x) needs to be triggered in order to store data using $.post(). The issue at hand: If I set the s ...

Initiating a conversation from deep within a conversation using JQuery Mobile

I've been attempting to open a Dialog from within another Dialog, but so far no success. Take a look at the HTML code below: <a href="#popupDialog" data-rel="popup" data-position-to="window" data-role="button" data-inline="true" data-transition=" ...

Setting the root route in express.js is a simple process that involves defining the

As a newcomer to express.js, I'm facing a challenge that has been puzzling me for almost 4 hours. My express server is meant to serve a build of a react app. To determine whether the user is not a bot, I am utilizing the useragent library. The code ...

Encountered an issue when attempting to select the password field in order to log into a Google account using

Having some trouble automating the login process for my Gmail account. Managed to find the email element with an ID, but hitting a roadblock trying to locate the Password element as it doesn't have an ID. Here's what I've attempted: passw ...

Troubleshooting: Issue with passing parameters in Wordpress ajax function

In my Wordpress Ajax implementation, I am facing an issue where the parameter value metakey: id is not being passed to $_POST["metakey"]. As a result, when I do a var_dump($_POST), it shows array(0) { }. If I manually set a static value for the variable i ...

What is the best way to incorporate Bootstrap 5 into a content script without causing any conflicts with the existing CSS of the website? (Chrome Extension)

In the process of integrating the Bootstrap 5 library into a Chrome extension, I have encountered an issue where the CSS and JS files conflict with the main CSS file on certain websites. To address this, I have included the Bootstrap 5 (CSS and JS) files i ...

Add empty objects to an array using a push function following the Vue JS constructor function

During my learning journey with Vue JS, I encountered an issue while attempting to populate an array with objects using a constructor function and the push method. Surprisingly, in Vue JS, the push function inserts a blank object into the array instead of ...

Difficulty altering link hover background color

I'm having trouble changing the hover effect background-color on the tweets of this page: Despite my efforts, all the links except for the latest tweets are working perfectly. What am I missing? Here's what I've been trying... <script& ...

What would be the counterpart of setLocale in Yup for the zod library?

How can I set default custom error messages for Zod validation? If I want to use i18n for error messages in Yup, I would do the following: import { t } from "i18next"; import * as yup from "yup"; import "./i18next"; yup.setL ...

How can you obtain values from a nested JSON object and combine them together?

I have a javascript object that is structured in the following format. My goal is to combine the Name and Status values for each block and then store them in an array. { "datatype": "local", "data": [ { "Name": "John", ...

Include a suffix after the user's input in a Material UI TextField

I need to implement a TextField element that displays the entered value followed by an Input Adornment. Can I have the percentage sign (%) appear after the entered value instead of at the end of the input? Currently, the percentage sign (%) appears at the ...

"Exploring the interactivity of touch events on JavaScript

Hi there, I'm currently facing an issue with the touch events on my canvas. While the mouse events are functioning correctly and drawing as expected, incorporating touch events seems to be causing a problem. When I touch the canvas, the output remains ...

The dimensions of GridStack items specified in pixels for both height and width

I am facing a challenge with my GridStack items, which each contain elements like graphs that need to be re-rendered when the size of the gridstack item (cell) changes. I am attempting to use the change event on GridStack to detect the modified items and t ...

What is the best way to pass an array as a parameter in Angular?

I have set up my routing module like this: const routes: Routes = [ { path: "engineering/:branches", component: BranchesTabsComponent }, { path: "humanities/:branches", component: BranchesTabsComponent }, ]; In the main-contin ...

Is there a way to execute the UNet segmentation model in Javascript using TensorFlow JS?

I recently trained a UNet model in Python and saved the model as a Model.h5 file. Following the instructions in the tensorflow JS documentation on How to import a keras model, I used the tensorflowjs_converter tool to convert the model into a Model.json fi ...

Managing an undetermined quantity of elements from a form in PHP

Currently developing an inventory page for my job. I've crafted a page that will iterate through my database and showcase all the items stored within. include 'auth.php'; //authentication required for login change $sql="SELECT * FROM `inven ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

Is it possible to invoke the same function twice on HTML5 Canvas?

I'm feeling overwhelmed as a beginner with HTML 5 canvas. I'm struggling with this particular function: function drawcircle(x,y) { context.save(); context.strokeStyle = '#00ff00'; context.fillStyle = '#000000'; ...

Having trouble capturing screenshots with PuppeteerJS?

I've encountered an issue while working with Puppeteer to capture screenshots from a provided URL. The code I have below doesn't seem to be functioning properly. It keeps showing the error message: [0] Error: Protocol error (Emulation.setDeviceM ...