Utilizing the $set method to capture a jQuery variable and append it to a Vue array object

Currently, I am retrieving data from an API using jQuery's getJson method to extract the information. After successfully obtaining the data, my aim is to assign it to a Vue array object by making use of app.$set.

Although I have managed to extract and store the data in the array, I am facing a limitation where I can only access one item at a time.

<div id="app">

    <div v-once id="movies">
        {{movieCall()}}
    </div>

    <div v-for="(movie,index) of movies" class="card" style="width: 18rem;">
        <!-- <img src="..." class="card-img-top" alt="..."> -->
        <div class="card-body">
            <div class="card-title">{{movie}}</div>
        </div>
    </div>
</div> 



var app = new Vue({
    el: "#app",
    movies: [

        ],
    },
    methods:
    $.getJSON("https://api.themoviedb.org/3/movie/now_playing?api_key=9d9f46b8451885697e5cf7d1927da80f", function (movie) {
        for (let i = 0; i < 3; i++) {

            app.$set(app.movies, i, movie.results[i].title);

        }

        for (var x = 0; x < app.movies.length; x++) {
            console.log(app.movies[x])

        }
    })

   }, 

My current approach involves extracting the movie titles and directly assigning them to the movie array. However, I would prefer to set up the array as an object with keys like title, description, etc., so that I can reference them more intuitively in my v-for loop.

app.$set(app.movies.title, i, movie.results[i].title);
app.$set(app.movies.description, i, movie.results[i].description);
etc.

This way, my movie array would be structured as:

movie[
      {title:}
      {description:}
]

And then I could iterate through it like this:

 <div v-for(movie, index) of movies>
 <div class="titles">
 {{movie.title}}
 </div>
 <div class="descriptions">
 {{movie.description}}
 </div>
 </div>

Answer №1

If you have a need to retrieve information on movies in this format:

<div v-for="(movie, index) of movies">
   ...
   {{movie.title}}
   ...
   {{movie.description}}

Then you can populate it like so:

app.$set(app.movies, i, {title: movie.results[i].title, description: movie.results[i].description});

Alternatively, if the value of i is increasing incrementally, you can achieve the same result with:

app.movies.push({title: movie.results[i].title, overview: movie.results[i].description});

Answer №2

Your code could use some improvements before it's good to go, so I've put together a snippet for you that achieves the same functionality (with a simulated JSON response). You'll notice that you don't actually need app or $set for this.

var app = new Vue({
  el: "#app",
  data: {
    movies: []
  },
  methods: {
    movieCall() {
      fetch('https://jsonplaceholder.typicode.com/posts')
        .then(response => response.json())
        .then(json => {
          json.forEach(movie => this.movies.push(movie))
          // alternatively:
          // this.movies = json
        })
    }
  },
  created() {
    this.movieCall()
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div v-for="(movie,index) in movies">
    <div>
      <div>{{index + ". Title: " + movie.title}}</div>
      <div>{{index + ". Body: " + movie.body}}</div>
    </div>
  </div>
</div>

I aimed to maintain the structure of your code as closely as possible (excluding CSS classes).

Essentially, Vue is reactive (utilizing the data property), so when you update the movies data, the template should instantly reflect those changes and update the UI. This concept lies at the heart of frontend frameworks like Vue.

Accessing data using dot notation (like movies.title) is a separate concept. In your project, you defined a data property - movies as an array. Arrays can store various types of elements, including objects.

The general approach is to fetch the objects and then populate the movies data property with them (one by one). Alternatively, if you receive an array, simply assign it to this.movies = response.

Furthermore, there's the notion of Vue templates having their own lifecycle, where created() serves as a hook to execute functions upon template creation. When you require certain actions to occur only once, leveraging these lifecycle hooks is essential. (Note that if your application reloads the template, the hook will run each time. To prevent redundant downloads, delve into state management, which is a broader topic on its own.)

Answer №3

Include a data key to store the dataset

 <script>
       var app = new Vue({
            el: "#app",
            data: {
                movies: [],
            },
        methods:
          $.getJSON("https://api.themoviedb.org/3/movie/now_playing?api_key=9d9f46b8451885697e5cf7d1927da80f", function (movies) {
              for (var x = 0; x < movies.results.length; x++) {
                //console.log("\nTitle"+movies.results[x].title);
                //app.movies.$set(x, movie.results[x].title);
                app.movies.push(movies.results[x].title);
                console.log(JSON.stringify(app.movies)) 
            }
          })
        }); 
    </script>

Test it out with this command

app.movies.push(movie.results[i].title);

Here is an example or sample that I have created : https://plnkr.co/edit/EnepqQqXzEquJlxqjzn6?p=preview

Reference: https://v2.vuejs.org/v2/guide/list.html

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

Divergence in results: discrepancy found in the outputs of nodejs crypto module and tweetnacl.js

Consider this code snippet in nodejs: import crypto from 'crypto'; const pkey = `-----BEGIN PRIVATE KEY----- MC4CAQAwBQYDK2VwBCIEIJC52rh4PVHgA/4p20mFhiaQ/iKtmr/XJWMtqAmdTaFw -----END PRIVATE KEY-----`; // placeholder key function sign_message(m ...

The Angular directive is failing to refresh the data on the Google Map

I created a directive called "myMap" to incorporate a Google map into my application. However, I am facing an issue when attempting to update the longitude and latitude values for a different location using a controller function. The directive does not ref ...

Storing Vuex updates for multiple tabs - Tips and tricks

I am encountering an issue with my Vue app that uses Vuex. When I have multiple tabs open, any changes made to the store in one tab do not reflect in the other. Is there a way to ensure that the store/data is synchronized instantly across all tabs? const ...

Leverage the power of axios in your React application to retrieve information from an

I have been exploring how to use axios for fetching data from an API (https://reqres.in/) and displaying it in my React application. Previously, I used the fetch method in JavaScript to retrieve data from APIs. Despite trying various resources, I am unsure ...

"Implement a function in Node.js/JavaScript that creates a new JSON object if the ID matches with the ID of another

const data = [ { system: { id: "4gSSbjCFEorYXqrgDIP2FA", type: "Entry", content: { type: { name: "Author" } }, }, DataDetails: { shortSlugOption: { "en-us": "some value", "za-op": "random value" }, ...

Trouble toggling Reactstrap navbar in my TypeScript project using NextJS

I recently integrated Reactstrap into my NextJS TypeScript project and encountered an issue with the Navbar component. Despite following the example from the Reactstrap documentation, the mobile toggle menu does not open when clicked. Additionally, none of ...

Begin composing in Excel

I am looking to manipulate an existing Excel file by writing values from an array and closing it all on the client side. Here is the code snippet I have been using: for (var c=0; c<arrMCN.length; c++) { var mcnCreate = arrMCN[c]; var mcnNumber =mcnCre ...

Tips for consolidating multiple projects under one domain without incurring any additional costs

Good morning! In my quest to host multiple projects on a single domain, specifically xyz.com, I am faced with a dilemma. I have an outdated personal developer portfolio created with React, and a newer software built with Vue.js that I would like to use fo ...

The optimal method for selecting a button from a group of buttons on a calculator using pure JavaScript

I have developed an HTML/CSS code inspired by the Mac/Apple calculator design. It features buttons organized in 5 rows using flexbox. You can view my code on this codepen: <div class="wrapper"> <div class="calheader"> ...

How can I call a function from one Vue component in another component?

I have developed a component with the function "logout" as seen in the code snippet below: // @/component/Painel.vue <template></template> <script> export default { name: 'panel', methods: { logout: function () { ...

The HSET command in the Redis client for Node.js is not working

I have been developing a DAO (data access object) for the project I am currently working on, which acts as an abstraction of a redis database. Below is the code relevant to my upcoming query: var redis = require("redis"); var _ = require("underscore"); va ...

Undefined value is returned for Vue 3 object property

Is there a way to extract additional attributes from the Keycloak object ? Currently, If I try, console.log(keycloak) it will display the entire keycloak object. Even after reloading, it remains in the console. However, when I do, console.log(keycloak.t ...

The utilization of "startIcon" and "endIcon" from the <Button/> API of Material-UI is restricted

I've been trying to work with this React code for a single component, but no matter what I do, I keep getting the same warning. I even tried copying and pasting the example, but the warning persists and the icon is not showing up. Can someone please a ...

PHP-based user interface queue system

I am in the process of developing a website that enables users to manipulate a webcam by moving it from left to right. Each user will have a one-minute window to control the camera. I plan on implementing a queuing system on the site to ensure that users ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Display various MongoDB datasets in a single Express route

I currently have a get method in my Express app that renders data from a MongoDB collection called "Members" on the URL "/agileApp". This is working fine, but I now also want to render another collection called "Tasks" on the same URL. Is it possible to ...

The Vue application is encountering an unexpected error in Chrome that is puzzling me as I search for a solution

Currently, I am delving deep into learning Vue.js and have decided to revisit the documentation from scratch and work through it in reverse order. Below is the content of my index.html file: <!DOCTYPE html> <html lang="en"> <hea ...

Using AngularJS and D3 to create a custom directive that allows for multiple instances of D3 loading within Angular applications

After creating an angular directive for a d3 forced-directed graph and using the code provided here, I encountered some issues with multiple loads. The directive seemed to load six times each time it was initialized, causing performance problems. To addres ...

Images in the JavaScript menu are not remaining fixed in place

Can someone help me with my website? I'm having trouble with the menu for different pages, it should stay gray for the active page. It was working fine before I switched to Wordpress, but now I'm not sure what the issue is. Could someone take a ...

Enhance your Vue.js 3 tables with sorting, filtering, and pagination capabilities using this custom component

After extensive research, I am still unable to find an updated Vue.js 3 component that offers sorting, filtering, and pagination for tables without the need for additional requests to a backend API. The options I have come across either seem outdated, are ...