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

Error: An unexpected identifier was encountered while executing my function

I've been trying to implement a function that I found online, but when I try to run it in the terminal, I keep getting this error: /home/simone/gekko/strategies/high.js:10 sma: function(name, price, points) ^^^ SyntaxError: Unexpected identifier I ...

Array of JSON data passed in the request body

Recently, I have been attempting to pass JSON data to my req.body. The data structure is as follows: answers = ["A","B"]; //An array to be included in the JSON Object var Student_Answers = { //JSON object definition Answers: answers, matricNumber: ...

Different methods to send dynamically created vuejs array data to a mysql database

I'm currently utilizing this code in my LARAVEL project http://jsfiddle.net/teepluss/12wqxxL3/ The cart_items array is dynamically generated with items. I am seeking guidance on looping over the generated items and either posting them to the databa ...

Tips for integrating Chart.js into my AngularJS application?

I am a beginner with AngularJS and I'm currently developing an application on Ubuntu. While trying to add Chart.js using npm install chart.js, an error is being displayed as follows. npm WARN <a href="/cdn-cgi/l/email-protection" class="__cf_emai ...

The element 'flat' is not found within the specified type

My challenge involves utilizing the flat() method in a TypeScript script. In my tsconfig.json file, I have set the target to es2017 and defined an interface for the input variable. However, I keep encountering this error message: Property 'flat' ...

Using AngularJS to integrate a function within a component

Hey there, I am facing an issue trying to call a function that is in a component. Let me share the code snippet from my component buttonsController: (function(){ "use strict"; angular .module('my') .component('myButton&ap ...

Enhanced hierarchical organization of trees

I came across this code snippet: class Category { constructor( readonly _title: string, ) { } get title() { return this._title } } const categories = { get pets() { const pets = new Category('Pets') return { ge ...

utilizing jQuery to create dynamic data changes based on JSON file

<div id="rightside"> <h1>John Doe</h1> <p>1980 - 2020 <p><a href="johnswebsite.com">Visit Website</a> <p>Lorem ipsum dolor sit amet, consectetur adi ...

Can you explain the significance of the "@" symbol prefix found in npm package names?

While reading through the Angular Component Router documentation, I came across an npm command that caught my attention: npm install @angular/router --save I'm puzzled by the meaning of @angular/router. Is this entire string a package name? If so, ...

Logging DOM elements with Electron's webview preload feature

Within my Electron program, I am utilizing a webview in my index.html file. The webview is equipped with a preloader, and my goal is to manipulate the DOM of the webview specifically, not just the index.html file. In my preloader code snippet below, the c ...

Adjust a sub-document field using mongoose

My foundational structure var GameChampSchema = new Schema({ name: String, gameId: { type: String, unique: true }, status: Number, countPlayers: {type: Number, default: 0}, companies: [ { name: String, login: String, pass: ...

How can "this" be properly utilized in jQuery?

I am attempting to retrieve the title attribute of an element from various elements with the same class, each having different attributes. This is my current approach: HTML <div title="title1" class="pager" onclick="location.href='link.aspx& ...

Encountering difficulties in transferring bulky files with the request module in Node.js

When working on a Node.js project, I encountered an issue with transferring files from the computer to the server. While I am able to successfully send files that are up to 2mb in size, larger files fail to upload. Here is the code snippet I am using: var ...

A unique Javascript feature that switches the text on various buttons

As someone who is relatively new to Javascript and web development, I am currently working on a project that involves creating multiple text areas for users to input and save text. Each text area is accompanied by a button with a unique ID that functions a ...

How to customize the background of radio buttons in HTML

I want the background color to stay consistent as lightgray for each <ul>. Currently, clicking the radio button causes the ul's background to change incorrectly. I am unsure of how to loop through all available ul elements using jQuery and woul ...

What is the best way to streamline the if statement in JavaScript?

Here is the given code snippet: public noArtistBeingEdited(): boolean { if (this.isFirstNameBeingEdited()) { return false; } if (this.isLastNameBeingEditable()) { return false; } return true; } What are some ways to ma ...

Is it possible to view newly added text in real-time on a separate client in Node.js without relying on socket.io?

I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem ...

How to style the first dropdown value in AngularJS to appear bold?

Is there a way to style only the first value in a dropdown list as bold without using jQuery? Here is the code for the dropdown: <div class="col-xs-3"> <select-box id="ad-version-select" options="curItem.stats.version" model="state.version" i ...

contenteditable -- Utilizing AngularJS to create a block element for the title only

When I click on an input field that is editable, I want the background color to change to white within the box. Can someone please assist me with this? Below is my code: HTML <div id="section{{section.index}}"> <h2 class="title" contentedit ...

How to use the filter() method to filter an array of objects based on a nested array within each object

The following data presents a list of products along with their inventory information: const data = [ { id: 1, title: "Product Red", inventoryItem: { inventoryLevels: { edges: [{ node: { location: { name: "Warehou ...