Vue.js routing and mixin dilemma

Calling all Vue developers! I am currently working on a vuebnb tutorial and running into an issue with routing and mixins. I have attempted to assign data before entering the router using the beforeRouteEnter guard, but it seems like my template is being rendered before the data is assigned. Below is the code snippet I have been trying:

ListingPage.vue

<template>
  <div>
    <img :src="'/' + images[1].img_path" />
  </div>
</template>
<script>
import { populateAmenitiesAndPrices } from "../js/helpers";
import routeMixin from '../js/route-mixin';

export default {
  mixins: [ routeMixin ],
  data() {
    return {
      title: null,
      about: null,
      address: null,
      amenities: [],
      prices: [],
      images:[],
    }
  },
  methods: {
    assignData({ listing, images }) {
      console.log('inside_component_before_assign');
      this.images = [...images];
      Object.assign(this.$data, populateAmenitiesAndPrices(listing));
      console.log('inside_component_after_assign');
    }
  },
  components: {
  }
};
</script>

route-mixin.js

import axios from 'axios';

function fetchData(to) {
    return new Promise((resolve) => {
        let serverData = JSON.parse(window.vuebnb_data);
        if (!serverData.path || to.path !== serverData.path) {
            axios.get(`/api${to.path}`)
                .then(({ data }) => {
                    resolve(data);
                });
        } else {
            resolve(serverData);
        }
    });
}
export default {
    beforeRouteEnter: (to, from, next) => {
        console.log('before_next');
        fetchData(to)
            .then((data) => {
                next(component => {
                    component.assignData(data);
                });
            });
        console.log('after_next');
    }
};

In the above code snippet, the data object has structure like {listing: {...}, images: Array(5), path: "/listing/1}. Server data fetching is validated. However, upon rendering ListingPage.vue, an error is thrown in the console: *

 [Vue warn]: Error in render: "TypeError: Cannot read property 'img_path' of undefined"

 found in
 ---> <ListingPage> at resources/assets/components/ListingPage.vue
       <App> at resources/assets/components/App.vue
         <Root>

The page still displays successfully despite the error. Any assistance on resolving this error would be greatly appreciated. Thank you!

Answer №1

After reviewing your comment reply, it seems like your issue was resolved by including a v-if in your HTML tag?

To implement this change, adjust your code to the following:

 <img v-if="images[1]" :src="'/' + images[1].img_path" />

This should resolve the issue, since the asynchronous request may not be fulfilled at the time the page is compiled by Vue. Refer to the Vue component lifecycle for more information.

Since data attributes are reactive, your component will become visible and the value will update slightly after compilation.

I would appreciate any suggestions on alternative approaches, as I am uncertain if this is considered best practice.

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

"Rearranging the Firefox ghost image by dragging and dropping it

My drag and drop game is working perfectly on all browsers except for Firefox. In Firefox, the ghost image that appears when an item is dragged seems to be positioned very far away from the cursor. Although the ghost image can still be seen on the page, it ...

Module-bound changes in Vuex go unaffected by global alterations

In my project, I've implemented a UserDialog component that relies on a specific section of the Vuex state tree to determine whether it should be displayed. Here is a snippet of the component code: import { Component, Prop, Vue } from 'vue-prope ...

Performing a validation on data fetched using a .load() function

I've been struggling with a persistent issue that I just can't seem to solve. So, here's the situation: I have a blog post on a CMS that I'm developing. The content is saved within a div with its own unique ID. When the user clicks an ...

Elements listed are often ignored by HTML

My website sends a URL and xpath query to the server in order to extract data from the URL based on the xpath query. While it is functioning properly, I am encountering a singular issue. When I specify an xpath query for href,text, it displays a list of a ...

Adjust the height of Revolution Slider on mobile devices using initialization

To see an example of the Revolution Slider, please check out the top hero section on this page. If you are looking for the initialization code, you can find it in this javascript file: function dz_rev_slider_5(){ if(dzQuery("#rev_slider_11_1" ...

Don't forget to save the selected date in the datepicker

I have a datepicker with two text fields: fromdate and todate. When I input the month of May and submit, then input another date, the default date should remain as May, instead of changing to the current month. Check out my code below. $(function() { ...

Assigning a Node.js exported function to a variable

Is there a way to save an exported function as a variable without executing it right away, in order to use Promise.all? I noticed that when I assign the function to a variable, it automatically runs. How can I prevent this from happening during assignment? ...

getting data from JavaScript function by making an asynchronous request to RESTful API

My current challenge involves calling a JavaScript method that utilizes AJAX to access a REST service and then return the response to the original call. While this may seem straightforward, I have scoured Stack Overflow for answers but haven't found a ...

Maximizing the potential of NestJS apps with Docker

I am working on a NestJS project that consists of multiple apps structured as follows: my-project: -- apps; --- app-one ---- src ---- tsconfig.app.json --- app-two ---- src ---- tsconfig.app.json -- libs -- package.json -- etc... Within this project, I ha ...

Creating a fresh array by applying a filter and assigning keys

I am facing an issue with my array structure, it looks like this, [ [ "Show/Hide", "P000", "MAX-CT05 FVM2-", "S", 1532, -9.5929406005, null, null, ...

Angular is notifying that an unused expression was found where it was expecting an assignment or function call

Currently, I am working on creating a registration form in Angular. My goal is to verify if the User's username exists and then assign that value to the object if it is not null. loadData(data: User) { data.username && (this.registrationD ...

Is there a way to initiate an AJAX post request with the Authorization header for the initial request using Windows Authentication?

I'm working on a web application that has a video page and a Web API for logging purposes. The events are triggered using an ajax post request: function logAction(actionToLog) { $.ajax({ type: 'POST', url: "/api/v/" + cu ...

Guide to using AJAX to send a select tag value to a PHP script on the current page

Issue I am facing a problem where I need to utilize the select tag in order to choose a value and then send that value via an ajax call to a PHP script embedded within the same page. In my code, I have implemented the select tag and upon selecting a valu ...

Exploring nested JSON information through jQuery's AJAX call

I am encountering an issue with accessing JSON data using a jQuery AJAX request in JavaScript. I keep receiving a 'Cannot read property [0] of undefined' error in the console of Google Chrome. Despite trying different approaches, such as referrin ...

When attempting to upload a file in Vue Apollo, a Node crash occurs with the error message "Maximum call stack size

I've been working on setting up the front end for graphQl file upload with Apollo-boost-upload. The backend code I'm using is based on this helpful tutorial: https://dev.to/dnature/handling-file-uploads-with-apollo-server-2-0-14n7. After adding t ...

Chrome experiences a hidden stalling issue due to a large WebGL texture

While working with WebGL on Windows 10 using Three.js, I noticed that initializing a large (4096 x 4096) texture causes the main thread of Chrome to stall for a significant amount of time. Surprisingly, the profiler doesn't show any activity during th ...

Having trouble configuring the proxy port for my Vue.js application

I'm currently developing a web application using vue.js for the front end and node.js for the server. Vue is running on port 8080 and Node.js is running on port 3001. To make API calls, I have set up a proxy in my vue.config.js file, but it doesn&apos ...

Surprising automatic scrolling upon pressing the keydown button in Bootstrap

My webpage appears normal with the Bootstrap framework, but whenever I press the down key, the screen scrolls down and displays unexpected white space due to reaching the end of the background-image sized at 1798px * 1080px. Please refer to the image: htt ...

Monitor files in different directories with the help of pm2

Can pm2 detect changes in directories outside of the current one? For example, if I have an index.js file in /home/sprguillen/workspace/node that needs to be run by pm2, but my configuration file is located outside in /home/sprguillen/workspace/config. I ...

Tips for utilizing CDN in vue cli?

My experience with packing frontend projects is limited. In the past, I only used JQuery for frontend development. Now, I have a project created by vue-cli and packed by webpack. I would like to load libraries from remote CDNs instead of my local server. ...