Exploring the selected object in VueJs

I am attempting to showcase a fullName function using the selected value

HTML :

<div id="test">
<h1>{{ sayHello }}</h1>

<select v-model="selected">
   <option v-for="person in persons" v-bind:value="person.about">
   {{ person.lname }}
   </option>
</select>
<p> {{ selected }} </p>

JS

New Vue({
  el: '#test',
  data: {
    selected : '',
    persons: [
      { fname: 'Foo' ,
        lname : 'Foo2',
        about : 'loren ipsum'},
      { fname: 'Bar' ,
        lname:'Bar2',
        about: 'dolor met'}
    ]  
  },
  computed :{
    sayHello : function() {
      return this.selected.fname + " " + this.selected.lname
    }
  }
})

h1 should return based on selected object value, this code returns undefined,(doesnt run at all if I pass in selected as arg) although the other parts work.Im not sure how to get the computed function to reference the selected object?

Edit:After using the great suggestions,Added a codepen for anyone else who is just starting:

https://codepen.io/2f2f/pen/rQdKKw

Answer №1

The reason the code is returning undefined is because there is no reference to this.fname or this.lname - it actually refers to the data object which only contains selected and persons.

To resolve this issue, you can use the selected variable to hold the person from the loop. This way, in your method, you can access the person's first and last names, but you'll need to adjust the bind value accordingly.

Here is a suggested modification:

new Vue({
  el: '#test',
  data: {
    selected : '',
    persons: [
      { fname: 'Foo' ,
        lname : 'Foo2',
        about : 'loren ipsum'},
      { fname: 'Bar' ,
        lname:'Bar2',
        about: 'dolor met'}
    ]  
  },
  computed :{
    sayHi : function() {
      return this.selected.fname + " " + this.selected.lname
    }
  }
});
<script src="https://unpkg.com/vue"></script>

<div id="test">
<h1>{{ sayHi }}</h1>

<select v-model="selected">
   <option v-for="person in persons" v-bind:value="person">
   {{ person.lname }}
   </option>
</select>
<p> {{ selected.about }} </p>
</div>

Answer №2

First name and Last name are not defined within the data object. This means that this.fname and this.lname will always return undefined. To resolve this issue, you must first identify the selected person object based on the selected value, and then retrieve the full name using the fname and lname properties.

new Vue({
  el: '#test',
  data: {
    selected : '',
    persons: [
      { fname: 'Foo' ,
        lname : 'Foo2',
        about : 'loren ipsum'},
      { fname: 'Bar' ,
        lname:'Bar2',
        about: 'dolor met'}
    ]  
  },
  computed: {
    sayHi: function() {
      var selectedPerson = this.persons.find(p => p.about === this.selected)
      return selectedPerson ? selectedPerson.fname + " " + selectedPerson.lname : ''
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6b68785d2f3328332c2a">[email protected]</a>/dist/vue.js"></script>

<div id="test">
  <h1>{{ sayHi }}</h1>

  <select v-model="selected">
     <option v-for="person in persons" v-bind:value="person.about">
     {{ person.lname }}
     </option>
  </select>
  <p> {{ selected }} </p>
</div>

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

Searching for a specific value in various Json files: A guide

My goal is to create an application where users can input longitude and latitude coordinates of a location, and the application will return the associated grid code from one of three JSON data files. I am attempting to search through all three files simult ...

Receiving a 200 response code, however the controller's store() method is not being accessed

Recently, I made the decision to switch from using a form in a blade file to a Vue-based form that utilizes Axios for posting data. After making these changes, I encountered an issue where I receive a 200 response, but my controller's store() method i ...

Vuejs v-model input value does not refresh dynamic data updates

I am currently working on incorporating the "pokemonName" parameter into the API URL that is being accessed through axios. The aim is to showcase the JSON data for each newly entered Pokémon by the user in a text input field. Below is my HTML code: &l ...

Execute the function only in response to changes in the data

I have a scenario where I am making an ajax call every 3 seconds to keep my app updated with rapidly changing information. However, the expensive function that I run inside the $.done() callback is causing my app to slow down. I want to optimize this proce ...

Updating the quantity of a product within a state in React allows for easy manipulation of that

My scenario involved attempting to reduce the quantity of a product object in the UI by clicking a button, but the quantity did not update as expected. What is the recommended course of action in situations like this? let product={ a:1,b:2,c:3}; For examp ...

Is there a way to adjust the contrast of an image using an HTML slider and JavaScript without utilizing the canvas element?

Looking to develop a slider with HTML and JavaScript (or jQuery, CSV,...) that can adjust the contrast of an image, similar to this topic. However, I would prefer not to utilize Canvas in HTML5 for this project. Any suggestions on how to achieve this with ...

Issues with Internet Explorer's scaling functionality are preventing it from operating correctly

I've utilized d3 to create a map. Its width is dynamically set based on the parent div's (with the id "map") width, and its height is calculated with a ratio of 5/9 in relation to the width. The viewBox attribute has been defined as "0 0 width he ...

Countdown component in Ant Design failing to display correct date

I’m currently working on developing a specific date component using react in conjunction with antd. Below is the code snippet I am utilizing: import { Statistic, Col, Row } from 'antd'; const { Countdown } = Statistic; const deadline = Date.pa ...

Encountering an issue when attempting to establish a connection to Redis using a cache manager within a Nest

Incorporating the NestJS framework into my project and utilizing Cash Manager to connect with Redis cache. Successfully connected with Redis, however encountering an error when attempting to use methods like set/get which shows 'set is not a function& ...

Prevent the form from refreshing while still allowing for submission

I'm currently working on a radio website that features a player and several banners that can be clicked on to play different radios. In my opinion, the ideal behavior would be that when I click on a button to play a radio, it should smoothly transiti ...

The process of webpack compiling a Vue.js project

Regarding webpack and vue.js usage, I am curious about how webpack builds a project when the npm run build command is executed. It is my understanding that a build folder must be included in the project with config files, and an output folder named dist is ...

Working with Java to parse non-strict JSON data that does not have keys enclosed in quotes

I am currently facing the challenge of parsing a string in JSON format where keys are not enclosed in quotes. While I have successfully parsed this string in Javascript, I am struggling to find a Java API that can assist me with parsing. The APIs I have at ...

Building a NodeJS powered single page application that consumes API data

Currently, I am working on developing a single-page JavaScript web application that will periodically fetch data from multiple public and possibly private APIs. The objective is to display and update this data in various tables. I could opt for creating th ...

jQuery ajax doesn't function properly on the server, it only works locally

When I send a jQuery Ajax request from my front-end to the back-end to retrieve values for calculations, it works perfectly on my local web server. However, when I try it online, all I get is a result of 0 in my calculations, indicating that the Ajax respo ...

I am attempting to activate the HTML5 color picker's popup using JQuery

Is there a way to open a color picker in a popup window when an input[type=color] is clicked, using JavaScript? HTML <div id="customColorPick"></div> <input id="customColorPickInput" type="color" /> JQuery $("#customColorPick").click( ...

employing this for the second parameter

Utilizing this.value for $(".selector") is my goal with $("#style_background") serving as my save button. However, when I implement this code, the value coming through is 'save'. How can I achieve this using dania and seablue? $("#style_backgrou ...

Scaling a mesh and BufferGeometry vertices using THREE.OBJLoader

Utilizing the THREE.OBJLoader, I successfully loaded a 3D model into my scene. Subsequently, I have the necessity to scale it by 10 and then extract its vertices position. I am aware that the THREE.OBJLoader provides a BufferGeometry, allowing me to acce ...

Showcasing the values of JavaScript

How can I resolve the issue depicted in the second picture? I need the value of 3 only in the USD column, with all others having a value of zero. <div class="span3"> <ul class="nav nav-tabs nav-stacked" > <?php foreach ( ...

Display the output of an array in JavaScript within the same document

I am struggling to print the contents of a JavaScript array data: [ JSON.parse(genreCanvas.dataset.count).forEach(count => { `${count},\n`; }) ], to achieve the following result: data: [ 1, ...

What is the best method for deactivating a button in discord.js after a 5-second delay?

Could use some assistance with discord.js buttons as I am unfamiliar with them. I need to figure out how to disable a button after 5 seconds to prevent spam in my code below: const newEmbed = new Discord.MessageEmbed() .setColor('#2ACAEA') .s ...