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

Issue with konvaJS when trying to simultaneously resize, drag, and apply filters to an image

Looking for help with resizing, dragging, and filtering images using Konvajs 2d canvas library? If the images are not resizing properly after applying a filter, can someone assist me? Note: Please be aware that when using Google image URLs, there may be c ...

Creating an array to store folder names that are exploding with path complexity

Here's a file path I need to work with: /www/htdocs/nether/http/helloworld/application/views/scripts/index/dashboard-stats.phtml I want to extract the "helloworld" folder name and store it in an array element. The challenge is that the position of ...

Guide to importing a JSON file in a Node.js JavaScript file

I am trying to incorporate a JSON file into my JavaScript code in a Node.js application. I attempted to include it using the "require();" method, but encountered an issue: "Uncaught ReferenceError: require is not defined". ...

The button is effectively disabled for a few seconds as needed, but unfortunately, the form cannot be submitted again using that button

The button is disabled for a specific duration as required, but the form does not get submitted through that button again. Below is the script code written in the head tag $(document).ready(function () { $('.myform').on('submit', ...

Generating a collection of objects using arrays of deeply nested objects

I am currently working on generating an array of objects from another array of objects that have nested arrays. The goal is to substitute the nested arrays with the key name followed by a dot. For instance: const data = [ id: 5, name: "Something" ...

Managing the Vuetify select value: assigning to an array or object

Here are the codes I am using: <template> <v-col cols="12" sm="6" md="3" class="px-1 text_details_color3"> <v-select :items="items" :label="lang.category" ...

Create a correct v-model value by utilizing a dot notation string as a reference to the data object

Recently, I created a proxy-component that dynamically renders different components based on the specified :type. Everything was functioning smoothly until I encountered an issue with nested objects within the formData object. An example of this problem i ...

Navigate the child div while scrolling within the parent div

Is there a way to make the child div scroll until the end before allowing the page to continue scrolling when the user scrolls on the parent div? I attempted to use reverse logic Scrolling in child div ( fixed ) should scroll parent div Unfortunately, it ...

Is it possible to alter the appearance of my menu when clicked on?

Is there a way to update the appearance of an active menu or submenu that is selected by the user? I would like the chosen submenu and its parent menu to have a distinct style once clicked (similar to a hover effect, but permanent). /*jQuery time*/ $(do ...

What are some strategies for blocking URL access to a controller's method in Rails 3?

My goal is to enhance my Rails 3 application by integrating Javascript/jQuery code that retrieves data from the server and updates the page based on the fetched information. I am considering implementing jQuery's $.get() method for this purpose: $.g ...

Angular is unable to eliminate the focus outline from a custom checkbox created with Boostrap

Have you noticed that Angular doesn't blur out the clicked element for some strange reason? Well, I came up with a little 'fix' for it: *:focus { outline: none !important; } It's not a perfect solution because ideally every element sh ...

What are the benefits of using a combination of design patterns in JavaScript?

Currently, I am working on a personal project for learning purposes, which is a simple To-Do List. I am implementing the modular pattern (specifically, the revealing module pattern). The image below showcases my general idea of how I intend to build it. V ...

Retrieve all values for a specific parameter in JArray

When I receive a JArray object from an edit control on the front-end, my goal is to extract and combine all the "text" values. The desired output should be a single string: "Established in 1995, the Elephant Sanctuary in Tennessee has provided ...spans 2 ...

Storage in private Safari mode is not synced between tabs on mobile devices

In the private mode of mobile Safari, I have successfully stored data in the localStorage. However, when I open my web app in two separate tabs, I notice that the data stored in one tab is not accessible in the other tab. This behavior may be present in ot ...

Is it possible to organize and filter a dropdown menu in JQuery based on a secondary value (new attribute)?

Can the drop-down list be sorted by value2? <select id="ddlList"> <option value="3" value2="3">Three</option> <option value="1" value2="1">One</option> <option value="Order_0" value2="0">Zero</option> </sele ...

Utilizing Vue CLI plugin to dynamically pass JS variables as props

I am currently using version 4.5 of the Vue CLI plugin. I have created a component that takes in a title as a prop. This component has been converted into a web component and added to an HTML webpage (which is not a Vue JS project) Now, I am attempting to ...

Ensure you are focusing on elements exclusively contained within the parent table and not any child tables nested within its cells

Looking for some help with a unique situation here. I'm struggling to find the right selector for this task. For reference, you can check out the jsfiddle at this link: http://jsfiddle.net/NZf6r/1/ The scenario is that I have a parent table containin ...

Using Next.js: What is the process for dynamically registering the quill-blot-formatter to react-quill that has been imported on the client side rendering exclusively

Currently, I am dynamically importing the react-quill library on the client side only by setting ssr: false. My functional component is functioning properly, but I now want to integrate the quill-blot-formatter package into the modules section of my quill ...

What is the most effective method for serializing SVG data from the client's Document Object Model (DOM

As I delve into the world of creating interactive SVG/AJAX interfaces, I find myself faced with a challenge. Users are constantly manipulating elements on-the-fly and I want to give them the option to export their current view as a PNG image or an SVG docu ...

Retrieve nested JSON data from an AJAX request

Currently, I am working with an API that provides JSON data back to me. The challenge I'm facing is figuring out how to access this data and showcase it on my HTML webpage since the results are stored in server memory rather than a file. Below is an e ...