How can you access the bound value in Vue JS?

I am struggling to access and display the value of model.title in the console when a click event is triggered. In my json file, there are a total of 3 records. The first model's title is IRIS. When I click on the link, I want it to be displayed in the console as well. Can someone please assist me with this issue?

<div id="app">

            <div v-for="model in myData">

          <h1>{{model.title}}</h1>
          <p>{{model.project}}</p>
          <p>{{model.bedrooms}}</p>
          <a href="#" @click="getTitle">View Detail</a>


        </div>


    </div>

 var vm = new Vue({

        el:'#app',
        data:{
            myData:[]

        },
        created:function(){
        this.fetchData();
        this.getTitle();
         },

        methods:{
        fetchData: function(){
        var url='data.json';
        axios.get(url)
        .then(function(res){
        vm.myData= res.data.models;
        console.log(this.myData);

        });
     },
     getTitle:function() {
        var url='j.json';
        axios.get(url)
        .then(function(res){
        //vm.myData= res.data.models.getTitle;
        console.log(res.data.models.getTitle);

        });

     }

}



    });

The below code is from data.json file

{
    "models": [
      {
        "title": "IRIS",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 3

      },
      {
        "title": "LILAC",
        "project": "ABC",
        "category": "DOUBLE",
        "bedrooms": 4

      },
      {
        "title": "ASTER",
        "project": "ABC",
        "category": "SINGLES",
        "bedrooms": 4

      }
    ]
  }

Answer №1

Passing a variable in a method when clicked is possible

Here's an example:

<button @click="displayUserInfo(user)">Show Detail</button>

Then in the method:

displayUserInfo: function(user) {
   console.log(user);
}

Answer №2

To display your data, simply follow these steps:

<div id="app">
  <div v-for="item in dataList">
    <h1>{{item.title}}</h1>
    <p>{{item.project}}</p>
    <p>{{item.bedrooms}}</p>
    <a href="#" @click="displayDetail(item)">View Details</a>
  </div>
</div>

var vm = new Vue({
  el:'#app',
  data(){
    return {
      dataList:[]
    }
  },
  created () {
    this.fetchData();
  },
  methods:{
    fetchData () {
      let vm = this;
      var url='data.json';
      axios.get(url)
       .then(function(response){
         vm.dataList = response.data.items;
         console.log(vm.dataList);
       });
    },
    displayDetail (item) {
      console.log(item.title)
    }
  }
});

Simplify your code by passing the data item as an argument to the displayDetail function when clicked, instead of calling it in the mounted hook.

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

What is the best method for rotating segments in THREE.TubeGeometry?

I've successfully generated a flat tube structure using THREE.TubeGeometry with radiusSegments set to 2. However, once added to the scene, it appears perpendicular to the ground: https://i.sstatic.net/U3qTt.png Is there a way to rotate each segment ...

Execute a function on a canvas timer using the setTimeout method

I'm having an issue with my setTimeout function in this code. I want it to call a timer function for a delay, but it's not working consistently every second. Why is that happening? <head> <script> function timer(sec) { var c = do ...

What is the process for including an external .js file in my VueJS2 index.html?

Currently, I am faced with a challenge involving two external Javascript files that are responsible for managing animations and vector triangulation for a background animation. In a typical html/css/js project, adding these two .js files would involve incl ...

finding the index of a particular checkbox in a list

I am working with a list of checkboxes that are dynamically created using JavaScript, each contained within its own separate div element. I need to determine the position number of a specific checkbox within all checkboxes sharing the same class within a p ...

Is there a way to retrieve text from within a div using code behind in asp.net with c#?

I am currently developing a SQL QUERY editor where users can enter queries. The entered text is then passed to a SQL COMMAND for execution, and the results are displayed to the user in a GRIDVIEW. However, I am facing an issue in retrieving the text entere ...

Monitor user inactivity with JavaScript

Our website contains iframe links to various content sites where users can take online exams. Some of these exams on the content pages run for over 3 hours. Additionally, an exam guard feature is implemented to prevent users from engaging in other activiti ...

Dynamic Visualizations with D3.js: Live Charts for Real-Time

This is my first time using D3.js and I am attempting to create a basic sparkline graph. The graph should have time on the X-axis and numbers up to 1000 on the Y-axis. I have a web socket server that sends random numbers up to 1000 to clients. My goal is t ...

Leveraging Selenium to dismiss a browser pop-up

While scraping data from Investing.com, I encountered a pop-up on the website. Despite searching for a clickable button within the elements, I couldn't locate anything suitable. On the element page, all I could find related to the 'X' to cl ...

Hover over to disable inline styling and restore default appearance

There are some unique elements (.worker) with inline styles that are dynamically generated through Perl. I want to change the background when hovering over them and then revert back to the original Perl-generated style. The only way to override the inline ...

TypeORM's Polymorphic Relationship fails to retrieve data from the parent entity

Currently, I am utilizing https://github.com/bashleigh/typeorm-polymorphic for handling polymorphic relations in my model. There are several models involved: // Device Entity @Entity() @TableInheritance({ column: { type: 'varchar', name: 'ty ...

A step-by-step guide on transforming an array of objects into an array of arrays with the help of Ramda

I want to convert the following data: [ { a: 2000, b: 4000 }, { a: 8000, b: 5000 }, { a: 6000, b: 1000 } ]; Into this format: [ [ 2000, 8000, 6000 ], [ 4000, 5000, 1000 ] ]; Using Ramda library. I am able to achieve this using R.reduce functio ...

Using Angular.js to trigger a callback function from a separate controller

Currently in my angular project, I am utilizing Angular.js material. I am trying to display a $mdialog with a custom controller, where the user can modify some data and have those changes applied to my $scope variable. This is an example of what I am doing ...

What is the best way to access an excel file using JavaScript and Protractor?

Is it possible to read an Excel file dynamically in JavaScript and iterate through cell values using row and column counts, without converting it into a JSON object? I have searched through several posts on Stack Overflow but have not found a solution yet. ...

transfer a product attribute value to a different product attribute within the Magento platform

There is an attribute called Weight : Attribute Code: weight Scope: general Catalog Input Type for Store Owner: Text Field Values Required: yes Apply To: Simple Product, Bundle Product Allow HTML Tags on Frontend: yes Also, there is a General Weight attr ...

What is the best way to restrict the size of a table that is filled with data from a database?

Currently using a combination of React, Node, Express, and Postgres to populate a table with data retrieved from Postgres. The issue arises when the table becomes overly long, prompting the need to display only 5 rows at once while adding a scroll bar for ...

HTML5 Positioning Timeout

While working on my project, I incorporated the HTML Geolocation feature. However, I have observed that it is not always dependable. I am looking for a solution to add a backup plan that will time out after x seconds and display an error message. Any sugg ...

How can I securely store passwords for web scraping with Puppeteer to ensure maximum safety?

Looking for advice on scraping a website that requires login. The current code saves username and password in a config JSON file, which poses a security risk if the file is accessed by unauthorized individuals. Is there a more secure method, such as encr ...

What is the best way to display JSON response as code instead of a string in AngularJS?

When retrieving my article from the database as a JSON object, I encounter an issue with the body content. The HTML codes in the body are displayed as strings within double quotation marks by AngularJS. How can I resolve this? Angular controller snippet: ...

How can I replay an HTML audio element?

I created an HTML5 page with an audio element for playing music in mp3 format. However, when the music plays to the end, it stops and I'm using JavaScript to control the audio element. Even so, I can't seem to replay it, only stop it. Is there a ...

When trying to retrieve a value from a custom render function in React with TypeScript, an error occurs indicating that the value is not assignable to type 'ReactNode'

Recently, I attempted to develop a versatile swiper component using Next.js 13 (App Router) v13.4.12 along with TypeScript. However, I encountered an issue when trying to access data from the component props, which involves a custom function for rendering ...