Tips for connecting Vue data to a dropdown menu

While diving into Vue.js, I'm encountering a puzzling issue. Despite receiving data from the server (5 records), it's not populating the <select> element properly. Instead of multiple options, all I see is a single one displaying {{dept.DName}}.

<html>
<head><link href="Content/bootstrap.min.css" rel="stylesheet" />
    <meta charset="utf-8" />
    <title></title>
</head>
<body class="container">
<div>
    <select id="deptList">
        <option v-model="selected" v-for="dept in app.depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>    
</div>
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/moment.min.js"></script>
<script src="https://unpkg.com/vue"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0e787b6b237c6b7d617b7c6d6b4e3f203d203a">[email protected]</a>"></script>
<script src="Scripts/vue-controller.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
</body>
</html>

The file vue-controller.js contains:

var app = new Vue({
    data: {
        el: "body",
        depts: [],
        emps: [],
        selected: ""
    },
    methods: {
        getDepts: function () {
            console.log("I'm a little teapot");  // this appears in the log
            this.$http.get("/Dept/Index").then(function(response) {
                this.depts = response.data;
                console.log(this.depts);  //the expected data does appear in the log
                },
                function(error) {
                    console.log(error.statusText);
                });
        }
    },
    created: function () {          
        this.getDepts();
    }
})

As a C# developer, I suspect I may be mishandling the this/that context, but I haven't been able to pinpoint the exact cause.

Answer №1

Here are a few things to consider:

  1. el is actually a root property of the Vue definition object, not a data property.
  2. Avoid binding to body as Vue will not allow it. Instead, bind to an appropriate element within the body content.
  3. The v-model directive should be used on the select element.
  4. You can reference all data properties by name directly in the template without the need for app.depts.

console.clear()

const departments = [
  {Did: 1, DName: "Department 1"},
  {Did: 2, DName: "Department 2"},
  {Did: 3, DName: "Department 3"},
]

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

  data: {
    depts: [],
    emps: [],
    selected: ""
  },
  methods: {
    getDepts: function () {
      console.log("I'm a little teapot");  // this appears in the log
      this.$http.post("https://httpbin.org/post", departments).then(function(response) {
        this.depts = response.body.json;
      },
      function(error) {
        console.log(error.statusText);
      });
    }
  },
  created: function () {          
    this.getDepts();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.9/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/1.3.4/vue-resource.js"></script>
<div id="app">
      <select  v-model="selected" id="deptList">
        <option v-for="dept in depts" v-bind:value="dept.Did">
            {{dept.DName}}
        </option>
    </select>  
    <hr>
    Selected Department: {{selected}}
</div>

Please note that I have adjusted the ajax call for compatibility with this environment. Assuming you are using VueResource, your original code for the ajax portion seemed fine.

Answer №2

When working with templates, variables are automatically scoped to "app", meaning you don't need to include "app." in your template code. Simply remove "app." from your template like this:

<select id="deptList" v-model="selected">
  <option v-for="dept in depts" v-bind:value="dept.Did">
    {{dept.DName}}
  </option>
</select>

Answer №3

Parent select element will have information about the item!

 <select v-model="item.selectedPersonId">
    <option v-for="(item, index) in personList" v-bind:value="item.personId">
          {{ item.personName }}
    </option>
 </select>

Below is the corresponding JavaScript code:

var app = new Vue({
    el : "#elemName" , 
    data : {
          personList : [{personName = "Name1" , personId = "1"} , 
                        {personName = "Name2" , personId = "2"} ] , 
          selectedPersonId : 0
    }
});

This implementation worked well for me. I appreciate the functionality provided by Vue.js.

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 VueJS components not functioning as expected with routes

I've encountered an issue when using the component tag with an id of #app within the template of my components/App.vue file. Whenever I include this setup, I receive the following errors: // components/App.vue <template> <div id="app"> ...

Using jQuery to dynamically add or remove table rows based on user inputs

Apologies if this is too elementary. I am attempting to insert rows into a table if the current number of rows is less than what the user requires. Simultaneously, I need to remove any excess rows if the current number exceeds the user's specificati ...

What is the proper way to delete a callback from a promise object created by $q.defer() in AngularJS?

When working with AngularJS, the $q.defer() promise object has the ability to receive multiple notify callbacks without overwriting previous ones. var def = $q.defer(); def.promise.then(null, null, callback1); def.promise.then(null, null, callback2); If ...

Using Node JS to retrieve JSON data from index.html upon button click

I'm currently learning the ropes of Node.js and want to set up a server where users can navigate to http://localhost:8000/ and be directed to index.html. In that file, there's a button to access JSON data. I plan to download this JSON data onto m ...

Implementing automatic token refreshing and automatic logout features in Vue

I am a novice web developer looking to enhance my skills. For my initial project, I decided to incorporate Laravel and Vue. My main objectives are to: Implement an auto-logout feature after 3 minutes of user inactivity Create an automatic ping to my token ...

Create your own custom block on the frontend product page

I am trying to create a custom block on the Product Page of my Magento store. I attempted it like this: Magento- How can i add a new custom block in product details page using module Unfortunately, it did not work as expected. Did I make any mistakes he ...

Help with iterating over an array containing unique URLs, and set the `window.location.href` to each URL as we loop through the array

Do you have a question that needs answering? It may seem simple at first glance, but I've been struggling to find a solution. My goal is to create a PHP loop where the "$ad_id" varies each time the loop is executed. Then, I want to display a button ea ...

Utilizing JavaScript to conceal div elements within a ul container

How can I hide specific div tags inside a ul tag using JavaScript? All div tags are currently getting hidden when I use the id of the ul tag. However, I need only the first div tag to be shown and the rest to be hidden. Here is the HTML code: <ul clas ...

Troubleshooting: Google Tag Manager showing a blank page

After attempting to integrate Google Tag Manager into my website, I encountered a strange issue where upon refreshing the page, it would go completely blank with no specific error displayed. I followed the only upvoted solution from a thread on Stack Over ...

Babel not functioning properly with static class property

I'm utilizing JSDOC along with all its supported npm plugins to generate comprehensive documentation. However, I've been facing difficulties when running jsdoc and parsing JSX files, as it consistently throws an error near the "=" sign as shown b ...

JQuery does not immediately update the input value

I'm working on a jQuery placeholder that mimics the behavior of default placeholders in Chrome and Firefox for browsers that don't support it. However, I'm facing an issue where the placeholder div's HTML doesn't change as quickly ...

The React Router onEnter Function Error: "Maximum call stack size exceeded"

I'm currently checking if a specific configuration value is set, and if it is, I want to redirect to a child route. If not, the page should display as usual. However, when I implement this code, the URL updates as expected but then seems to get stuck ...

Can JavaScript be used to determine if any code has been executed from the browser's console?

I'm currently developing a JavaScript game and I want to prevent cheating. Is there a way for me to track and record commands entered in the JavaScript console? Here's a basic outline of what I have in mind: consoleCommands = ""; window.console ...

Navigating JSONP using jQuery

I'm encountering an issue where I can see the correct response in Firebug, but I'm unable to access the data it returns. I need some guidance on how to achieve this. Specifically, I'm attempting to place the timestamp of an entry into a div ...

JavaScript - Utilizing an image file in relation to a URL pathway

Is there a way to reference an image URL using a relative path in a JavaScript file similar to CSS files? To test this, I created two divs and displayed a gif in the background using CSS in one and using JavaScript in the other: -My file directory struct ...

Troubleshooting ng-class functionality in AngularJS

I am attempting to utilize AngularJS in order to change the class name of a div element. Despite following the guidance provided in this answer, I am encountering difficulties as the class name is not updating in my view. Below is the code from my view: ...

Dynamic field refreshed on server side upon second button press

I'm encountering an issue where a hidden field that I update via Javascript only reflects the new value after clicking a button twice. Surprisingly, I can view the updated hidden field value when inspecting it through the browser. Default.aspx <s ...

Getting started with WebTorrent: A beginner's guide

I have been brainstorming some ideas for using WebTorrent. While I am comfortable with JavaScript and jQuery, I have never ventured into Node.js or Browserify territory. Can someone guide me through how to implement the following straightforward code? var ...

What is the process for linking read-only methods to Redux object instances?

Let's say I have a "user" object stored in redux, with fields for first name and last name (interface User { firstName : string, lastName : string} if using typescript). After retrieving a user from redux, I want to obtain the full name of the user by ...

Can you explain the key distinctions among Highland.js, Kefir.js, and Rx.js?

Given the emphasis on objective answers on SO, my inquiry is focused on understanding the distinct functional and performance characteristics of these three functional/reactive libraries. This knowledge will guide me in selecting the most suitable option ...