The outcome of the mustache is stagnant and remains unchanged

While experimenting with Vue.js, I encountered a puzzling issue that has left me perplexed. Here is the code snippet that showcases the problem:

Vue.component('list-entry', {
  'template': '<input type="text" :value="t" @input="fireEvent()" ref="text">',
  'props': ['t', 'idx'],
  'methods': {
    fireEvent() {
      this.$emit('update:t', {
        'value': this.$refs.text.value,
        'idx': this.idx
      })
    }
  }
})

new Vue({
  el: "#app",
  data: () => ({
    texts: [
      'Foo', 'Bar', 'Baz'
    ]
  }),
  methods: {
    update(ev) {
      console.log('Set ' + ev.value + ' at index ' + ev.idx)
      this.texts[ev.idx] = ev.value
      console.log(this.texts)
    }
  }
})
input {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class='container'>
    <list-entry 
      v-for="(t, idx) in texts" 
      :key="t" 
      :t="t" 
      :idx="idx" 
      @update:t="update($event)"
      ></list-entry>
  </div>
  {{ texts }}
</div>

To provide some context, there is a global data property texts that holds multiple strings. Each string is passed to a unique custom component called list-entry using v-bind.

Whenever there's a change in the input text fields, the goal is to update the global data property dynamically. To achieve this, an update:t event is triggered and handled within the main app. The function update(ev) should take care of updating the data.

Upon running the code, you'll notice that the console displays the correct messages and the array is updated accordingly. However, the values do not reflect in the HTML output (replaced from {{ texts }}). This inconsistency has left me baffled. Is the data truly being updated? Why does it fail to render in the mustache notation but logs correctly in the console?

Answer №1

To achieve the desired functionality, a concise code snippet can be used by implementing v-model on components.

Vue.component('list-entry', {
  'template': `<input type="text" :value="value" @input="$emit('input', $event.target.value)" />`,
  props: ['value'],
})

new Vue({
  el: "#app",
  data: () => ({
    texts: [
      'Foo', 'Bar', 'Baz'
    ]
  }),

})
input {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <div class='container'>
    <list-entry v-for="(t, idx) in texts" :key="idx" v-model="texts[idx]"></list-entry>
  </div>
  {{ texts }}
</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

Emberjs promises are enhanced with a filtering feature

My goal is to develop a search functionality using a JSON API. After following tutorials and successfully implementing it with provided examples: export default Ember.ArrayController.extend({ searchText: null, searchResults: function(){ ...

Updating HTML content based on an active user session using Node.js/Express - A Step-by-Step Guide

I'm struggling to find a way to remove the login/signup buttons once a user has successfully logged in. The issue lies within my header file that needs some modification. <section class="header"> <div class="wrapper"> <nav ...

Order list based on matching keyword in data attribute

I am currently working with a lengthy list that utilizes basic JavaScript search functionality. The search function uses regex to check for specific conditions and hides items that do not meet the criteria. I am attempting to organize the list in such a wa ...

The dirtyVertices feature in Three.js seems to be malfunctioning

In my three.js project, I created a 12*12 plane and attempted to modify its vertices between two renderings without success. Despite adding the following code, no changes were observed: ground.geometry.dynamic = true; ground.geometry.__dirtyVertices = tr ...

Ways to insert a line break within a jQuery function using text()

I am looking to add a new line in my jQuery function. $.ajax({ url:"http: //192.168.1.4/Experiements/webservices/api.php", type:"GET", dataType:"json", data:{type:"login", UserName:userId,Password:userPassword}, ...

Issue with Angular modal text boxes failing to populate using ngModel

I am facing an issue with populating data in a modal when a table row is clicked. The table contains TV show data and uses dir-paginate/ng-repeat to display the information. However, when I click on a row to edit the show, the ng-model data does not load i ...

Uploading image files using Node Express and returning them as JSON in an API response

Is it possible to send json along with an image file in Express? I know that you can serve an image using res.sendFile const path = require('path'); app.get('/image/:filename', (req, res, next) => { res.type('png'); r ...

React: Row with dynamic content not loading properly

I'm having trouble getting a response when I click to execute the addRow() function. Can anyone spot what might be wrong with my code? ... constructor(props) { super(props) this.state = { rowCount: 1 } } addRow = () => this.s ...

Setting up a Firebase app across multiple files using Node.js

Trying to organize my methods properly, I want to Initialize Firebase App in multiple files. However, I'm unsure of the best approach. Here is the structure of the file system: /functions |-keys |-methods | |-email.js | |-logger.js |-node_mod ...

JavaScript Decoding JSON with varying identifiers

The JSON data provided contains information about different types of vehicles, such as cars, buses, and taxis. { _id:"7654567Bfyuhj678", result:{ CAR:[ [ "myCar1", 12233 ], [ ...

Discovering nested documents in MongoDB using JavaScript

How to find nested data in MongoDB with the following collection: { "_id": { "$oid": "585b998297f53460d5f760e6" }, "newspaper": { "playerID": "57bffe76b6a70d6e2a3855b7", "playerUsername": "dennis", "player_newspaper": "{\"ID\":\" ...

Nuxt's calendar feature

Posting my first question here. I'm currently working on creating a calendar in Nuxt for tracking registered hours. The code I've included below successfully creates the calendar, but I would like to modify the 'days' array to hold obj ...

Struggling to reflect changes in the database using the updated value in the localStorage

I have a table where the td is set to contenteditable. To update the value of the td in my database, I decided to use localStorage. When the save button is clicked, the inputted value in the td will be saved to localStorage and retrieved via AJAX to replac ...

Utilizing a RESTful approach for ajax requests is effective, but there seems to be a

Trying to make an ajax call and facing some challenges. Used a REST test extension for Chrome called Postman [Link to it]. While the call works fine with the extension, encountering an "error 0" message when trying to send it through jQuery. The request s ...

Discover the exclusive Error 404 dynamic routes available only in the production version of NEXT13! Don

Hey everyone, I'm encountering an issue with NEXT's dynamic routing (Next 13). My folder structure looks like this: - user/ -- [id]/ --- page.js It works fine in dev mode but not in production. What am I trying to do? I've created a "page ...

Is there a new update to Google Maps API?

After successfully building a map component for a web application using google maps, open layers, and the dojo toolkit, it suddenly stopped loading earlier this morning. Even though there are no JavaScript errors and open layers and Google still initialize ...

Encountered an issue while attempting to integrate Nebular into my Angular application

As a newcomer to Angular, I decided to try installing Nebular using the command ng add @nebular/theme. However, I encountered an error in the process. Upon entering the command into my terminal, the following error message appeared: ? Which Nebular theme ...

Switching visual representation that appears upon clicking the dropdown menu

Issue with Duplicating Dropdown and Image Change const image = document.querySelector('.item__img'); const checkbox = document.querySelectorAll('.imgOption'); function handleChange() { let imgsrc = this.getAttribute("data-value ...

Turn off the chrome react DevTools when deploying to production to ensure the

I have successfully browserified my react app for production using gulp and envify to set up NODE_ENV. This has allowed me to remove react warnings, error reporting in the console, and even disable some features like the require of react-addons-perf. Afte ...

Querying MongoDB to locate an element within an array is a common task

I need help with writing a mongoose query to select a specific object from the "cartItems" array in my mongodb database and update its "qty" and "price" fields. Here is the data: { _id: new ObjectId("634a67e2953469f7249c9a7f"), user: new ObjectId("634 ...