A guide on accessing objects from an array in Vue.js

Wondering how to choose an object from an array in Vue.js:

When the page loads, the selectTitle() function is triggered. I simply want to select a specific object (for example, i=2) from my 'titleList' array. However, at the moment, I am only receiving an Observer as the output. I understand it has something to do with the scope or binding, but as a newcomer to Vue (and JS!), could someone please assist me?

Thank you!

var vm = new Vue({
    el: '#titles',
    data: {
        titleList: [
            { title: 'Title1', details: 'details1', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
            { title: 'Title2', details: 'details2', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
            { title: 'Title3', details: 'details3', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
            { title: 'Title4', details: 'details4', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' },
            { title: 'Title5', details: 'details5', imgLocation:'', text: 'Lorem ipsum dolor sit amet.' }
        ],
    },
    mounted: function () {
        this.setTimer();
        this.selectTitle();
    },
    methods: {
        selectTitle() {
            let i = 2;
            let currentTitle = this.titleList[i];
            console.log(i, currentTitle);
            return currentTitle;
        },

Answer №1

It is completely normal and exactly what you would expect with Vue. Vue automatically wraps every object into an observable, so any changes to your data will automatically update all data-bindings in the view without any extra effort on your part. This acts as a proxy, allowing you to manipulate the object just like you normally would. For instance:

currentTitle.title = 'New Title'

This will properly update the attribute, and if you have a reference in your view, it will also update the view without needing any additional steps. That's one of the benefits of using Vue.

To better understand this concept, here's a codepen example that builds upon your code: Codepen Example

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

When should the grecaptcha.execute() function be invoked while utilizing Invisible reCAPTCHA V2?

I recently implemented invisible reCAPTCHA successfully, but I'm wondering if I did it correctly when calling grecaptcha.execute(). After loading the API script with an explicit call like this: <script src="https://www.google.com/recaptcha/api.js ...

Currently waiting for the $resolved property of the AngularJs service

Here's a straightforward issue with what I hope is an equally simple solution. I've set up multiple services for handling CRUD operations with tags. myApp.factory('GetTags', ['$resource', function ($resource) { return $re ...

Endless Loop: AngularJS app.run() Promise caught in infinite cycle

I have a situation in my AngularJS app where I am using app.run() to check if a user is logged in before displaying the site to restrict access to non-registered users. Initially, I faced issues with the isLoggedIn function returning false when reloading t ...

Interacting between Jquery and servlets using AJAX

In order to establish communication between a Jquery function and a servlet in Tomcat, I have created the following code snippets. Servlet Code: import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; i ...

Leveraging nested objects within React state

A React child cannot be an object. If you intended to render a collection of children, utilize an array Encountering the error mentioned above has left me puzzled regarding its restrictions. Below is the code where I am facing this issue. It includes an o ...

Error in Next.js: The element type is not valid. Please make sure it is either a string (for built-in components) or a class/function (for composite components) and not undefined

I've encountered an issue while working on my Next.js project where I am trying to import the Layout component into my _app.js file. The error message I received is as follows: Error: Element type is invalid: expected a string (for built-in componen ...

The JavaScript filter function will only return arrays that have matching IDs

How can I filter out book data based on the author's id? I have a list of books with various author ids, and I want to only return the books that match a specific author id. However, my current filtering method doesn't seem to work correctly as i ...

Disable system discord.js

Hey there, I'm experiencing an issue with my code and could use some help. Every time I try to use my mute command, it keeps spamming "You need permission to use command". Below is the snippet of my code: client.on('message', message => { ...

Step-by-step guide on redirecting to a different page following a successful POST API call using Jquery

I have the code below in my JavaScript file. $scope.addLookupAction = function () { $("#importForm").attr("action", 'xyz.com'); success:function(response) { $log.info("Redirecting to lookup home page"); ...

Issue with jQuery not being able to retrieve the data from my CSS property

this is my custom style code: table.table tr td{ padding:30px; border-left: double 1px white; border-bottom: double 1px white; cursor:cell; } and below is the jQuery script I am using: $(document).ready(function () { ...

What could be causing my click() function to only work properly after resizing?

It's driving me crazy. The code snippet below works perfectly, but not in my project. Only the code in the resize() function seems to work. When I resize the window, everything functions as expected - I can add and remove the 'open' class by ...

Static folder images not appearing in Nuxt 3

I am currently using Nuxt 3 and here is the directory structure I am working with This is how images are being loaded <img src="/images/index/pic-left.svg" /> I also attempted to remove the / at the beginning of the path <img src=&quo ...

What is the best way to concatenate a const character pointer array element with a const character pointer string?

I'm currently using ImGui and am attempting to include an array item to my const char * in order to display the selected item. However, instead of displaying what I want, it shows random letters. Any idea how I can fix this issue? static const char* F ...

"An ng-repeat directive with a filter applied results in an empty

After successfully implementing the ng-repeat loop below: <div ng-repeat="einschItem in einschaetzungen.alldata | filter: { savedatum: lolatage[tagarrayindex].tagestring } | orderBy : '-savetimestamp'"> I wanted to check if the filtered r ...

The creation of the ESLint CLIEngine encountered some issues

Encountered an issue while setting up the ESLint CLIEngine - 'basePath' must be an absolute path Attempting to utilize eslint $ npx prettier-eslint **/*.js However, receiving the following error message: prettier-eslint [ERROR]: Encountered a ...

Is iterating through object with a hasOwnProperty validation necessary?

Is there any benefit to using hasOwnProperty in a loop when an object will always have properties? Take this scenario: const fruits = { banana: 15, kiwi: 10, pineapple: 6, } for (let key in fruits) { if (fruits.hasOwnProperty(key)) { ...

What is the process for transforming a string into an array?

I have a string that looks something like this: $str = "<div> <b> <label>City : Paris</label> </b> </div> <div> <b> <lab ...

Prevent JavaScript Errors when performing a page postback

I am currently using the Telerik RAD Editor control in my ASP.NET 4.0 application, which is outside of any update panel. On the same page, I have multiple ModalPopUps and update panels to prevent unexpected full postbacks. The page contains PageMethods inv ...

Vue js: Stop Sorting array items; only display the resulting array

I recently came across a tutorial on voting for a Mayoral Candidate. The tutorial includes a sort function that determines the winner based on votes. However, I noticed that the sort function also rearranges the candidate list in real time, which is not id ...

Despite the updates, Express JS PUT request does not successfully save changes

Currently, I have an Express JS application where I am attempting to update an existing user's name using the PUT method. The schema I am working with is a nested array and is structured like this: https://i.sstatic.net/WDIse.png The code snippet I ...