Exploring the Functionality of Computed Properties in Vue.js

I am facing an issue with my Vue component where I am trying to set the image src using data from my api.

const product = computed(() => {
    return store.products.find(product => product.slug === route.params.slug);
});

const selectedImage = ref(null);

function setMainImage(image) {
    selectedImage.value = image.original_url;
}

onMounted( () => {
    selectedImage.value = product.default_image;
});

The data is visible in Vue dev tools:

product:Object (Computed)
    default_image:"http://localhost/storage/1/photo-1600210492493-0946911123ea.jpeg"
    description:"Lorem ipsum dolor sit ..."
    id:1

However, the image is not appearing in my component:

<img v-bind:src="selectedImage">

If anyone has any insights on why this might be happening, please let me know!

EDIT

Here is some information about the cart store:

import axios from "axios";
import { defineStore } from "pinia";
import { useStorage } from '@vueuse/core';

export const useCartStore = defineStore({
    id: 'cart',
    state: () => ({
        cart: useStorage('cart', { products: [], packages: [] }),
        order: {},
        customer: {},
        loading: true,
        error: null,
        categories: [],
        products: [],
        packages: [],
    }),
    actions: {
        async getProducts() {
            try {
                this.loading = true;

                const resProduct = await axios.get("/api/product");
                this.products = resProduct.data.data;

                const resPackage = await axios.get("/api/package");
                this.packages = resPackage.data.data;

                this.loading = false;
            } catch (error) {
                this.error = error;
            }
        },
...

Answer №1

RESOLUTION

After troubleshooting, I found a solution to the problem. I decided to eliminate the onMounted function and made adjustments to the product computed call:

const product = computed(() => {
    const product = store.products.find(product => product.slug === route.params.slug);
    if (product !== undefined) {
        selectedImage.value = product.default_image;
    }
    return product;
});

const selectedImage = ref(null);

Answer №2

Consider updating the product.value within the onMounted function.

onMounted(async () => {
    await product.value;
    selectedImage.value = product.value.default_image;
});

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

Unable to display information from a repeated `textarea` in ngRepeat

Check out my code on Plunker: https://plnkr.co/edit/rBGQyOpi9lS0QtnCUq4L I'm trying to log the content of each textarea when typing, using the printStuff() function: $scope.printStuff = function(customize, item) { console.log(customize[item.inde ...

Experiencing challenges with Vuetify layout: Having difficulty preventing 3 flex elements from exceeding the height of the screen

I'm currently facing some challenges with the vuetify layout grid. Within my component, I have a v-layout containing 3 v-flex elements. One for the toolbar (top), one for the content (middle), and another for the action bar (bottom). The issue I&apo ...

Encountering an error when attempting to iterate over an undefined property using an API

I am trying to fetch all classes and their assignments from Google Classroom. I successfully used Google's example code for listing the classes, but had to write my own code for listing the assignments. While the code runs as expected and lists the as ...

Adjust ChartJS yAxes "tick marks"

I'm having trouble adjusting the scales on my yAxes and all the information I find seems to be outdated. My goal is to set my yAxes range from 0 to 100 with steps of 25. Check out this link yAxes: [ { ...

Using regular JavaScript with code inside ng-view in AngularJS involves incorporating event listeners and manipulations that can interact

Just delving into the world of angularJS for the first time. I've set up the routing service, which involves having a div with routing that calls in a template containing HTML code. I also have a range of regular JavaScript functions necessary for the ...

Adding content to a text field and then moving to the next line

I am looking to add a string to a text area, followed by a new line. After conducting some research, here are the methods I have attempted so far but without success: function appendString(str){ document.getElementById('output').value += st ...

What methods can I use to evaluate my Angular scope functions in karma and jasmine?

I recently started learning Angular and am new to Jasmine testing. I have a function in my controller that adds an object from JSON data into an empty array. My controller with the cart-related functions: $scope.cart = []; $scope.addItemToCart = funct ...

Sending an Array from a ReactJS Frontend to a Django Backend using JavaScript and Python

I successfully created a website using Django and React JS. In my project, I am working on passing an array named pict from the frontend JavaScript to the backend Python in Django. let pict = []; pictureEl.addEventListener(`click`, function () { console ...

Creating a soft focus effect in a specific region (behind the text)

While working on my homepage created with HTML/CSS/Javascript, I have text positioned at the top left corner of the screen. The challenge arises from the fact that I am using different backgrounds sourced from Reddit, and a script randomly selects one duri ...

How can I place an Object in front of an Array in JavaScript?

Currently, I am working on an Angular project where I need to modify a JSON array in order to display it as a tree structure. To achieve this, the objects in the array must be nested within another object. Desired format / output: this.nodes = [ { id ...

Using React hooks to transfer an item from one array to another and remove it

export default function ShoppingCart() { const classes = useStyle(); const { productsList, filteredProductsList, setFilteredProductsList, setProductsList, } = useContext(productsContext); const [awaitingPaymentList, setAwaitingPaymentList] = us ...

Stop vuetify from cluttering the global style scope

Seeking to embed a Vue component into another from an external source without using a Vue Plugin. The components are mounting correctly, but the embedded component's use of Vuetify is affecting the parent application's style. Visual examples can ...

find all occurrences except for the last of a pattern in javascript

When considering the patterns below: "profile[foreclosure_defenses_attributes][0][some_text]" "something[something_else_attributes][0][hello_attributes][0][other_stuff]" It is possible to extract the last part by utilizing non-capturing groups: var rege ...

Activate the opening of a .docx file in a new tab by utilizing an anchor tag

I have attached a docx file containing the terms and conditions for our project. Now, I would like to open it in a new tab. By clicking this link, you can view the <a title="click to view terms and conditions" style="color:blue;" target="_blank" href ...

Facing a challenge with displaying an angularjs template within a popover

I am having trouble displaying custom HTML content in a popover when clicking on my "View" link. Although other content is rendering correctly, such as one with an ng-repeat inside it, my custom directive does not seem to be processed and displayed properl ...

After employing a combination of forEach and filter queries in JavaScript to sift through dropdown options, no results are being generated

Hey there fellow developers, I'm currently in the process of developing an app and have reached the stage where I am filtering elements using dropdowns. I am querying a JSON object and comparing it with the selected element in the dropdown at that mom ...

My middleware produces different results when used by Postman compared to when used by a Browser

Recently, I began delving into backend development using Node.js and Express. One of the tasks I wanted to accomplish was creating a middleware that would display a message in the console if a request was made to a route that doesn't exist. Here is wh ...

Are there any online tools available for generating SSJSON specifically designed for SpreadJS?

Currently utilizing Ubuntu, Ubuntu-Wine, and MS Office 7 on Wine. Interested in converting an xls template to ssjson for testing SpreadJS. Found some sjson file links on the Wijmo forum. Managed to successfully load it into SpreadJS, but unsure if the c ...

Guide to linking multiple images to a single Post instance

Is it possible to attach each array of images to their post using the foreign key placePlaceId? For example, in the first object with place_id:3, I want to attach all the images with the foreign key placePlaceId:3. This is my approach to achieving this go ...

Tips for accessing a web service using JavaScript (AJAX)

I have two projects: one is a web service and the other is an ASP.NET web project. I am trying to insert data using JSON (with AJAX). I tested the web service file with code behind and it works fine, but I'm encountering an error with the JavaScript ...