What is the best way to trigger a function after the v-model has been updated

When attempting to filter an array of objects in Vue using input, I encountered issues with Salvattore not functioning correctly for building a grid of the filtered elements. It seems that calling the rescanMediaQueries() function after changes to my v-model may solve the issue, but I am unsure of how to implement it.

Below is my Vue instance setup:

var articlesVM = new Vue({
      el: '#search',
      data: {
        articles: [],
        searchInput: null
      },
      ready: function() {

          this.$http.get('posts').then(function (response) {
            this.articles = response.body;
          });

      }
});

This is how the search feature has been implemented:

<div class="container" id="search">
  <div class="input-field col s6 m4">
    <input v-model="searchInput" class="center-align" id="searchInput" type="text" >
    <label class="center-align" for="searchInput"> search... </label>
  </div>

  <div id="search-grid" v-show="searchInput" data-columns>
    <article v-for="article in articles | filterBy searchInput">
        <div class="card">
            <div class="card-image" v-if="article.media" v-html="article.media"></div>
            <div class="card-content">
                <h2 class="card-title center-align">
                    <a v-bind:href="article.link">{{ article.title }}</a>
                   </h2>
                   <div class="card-excerpt" v-html="article.excerpt"></div>
            </div>
            <div class="card-action">
                <a v-bind:href="article.link"><?php _e('Read More', 'sage'); ?></a>
            </div>
        </div>
    </article>
  </div>

To address the issue, I tried utilizing the watch option in Vue, which solved the grid system problem. However, when entering and then deleting text from the input field, the filterBy method would stop working. Even re-entering the same keyword did not yield any results. Here is the watch option I utilized:

watch: {
   searchInput: function (){
       salvattore.rescanMediaQueries();
   }
}

Answer №1

It appears that the issue lies in how the scope of 'this' is handled within your success handler for the http request. The 'articles' object in your Vue component is not receiving any values from the successful http.get() call.

To resolve this, make sure to adjust your http success handler inside the 'ready' function as shown below:

this.$http.get('posts').then(response => {
  this.articles = response.body;  // 'this' refers to an outer scope
});`

Alternatively, you can use the following approach:

var self = this;  // 'self' now points to the 'this' of the Vue component
this.$http.get('posts').then(response => {
  self.articles = response.body;  // 'self' now references the 'this' of the outer scope
});`

If you encounter a similar issue in the future, consider defining data as a function for better isolation like so:

var articlesVM = new Vue({
  el: '#search',
  data: function() {
    return {
      articles: [],
      searchInput: null
    }
  },
  ...
}

This ensures that each instance of the component has its unique data, preventing issues when using the same component in multiple locations within your app.

The code snippet provided after addressing comment #1 seems to be functioning correctly. The 'watch' function operates smoothly with console logging messages upon input changes.

For ensuring compatibility between vue.js and salvattore plugin, consider introducing a slight delay before calling the plugin to adjust layouts post rendering using one of the suggested methods. This helps prevent interference with vue.js observers, getters, and setters.

Let me know if these solutions help resolve the issue!

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

The absence of a flickering flame is noticeable in the THREE.js environment

I have been working on creating a flame using THREE.js and spark.js. However, even after rendering the world, I am unable to see the flame and it seems like the world is empty. Although I checked the console for errors, there are no indications of what mig ...

How can we reset multiple selected values (mui chips) in a React Material-UI Autocomplete field when changing the value in a different field?

Is there a way to clear the mui-chips in Material UI Autocomplete TextField when the value in another field is changed? I have been struggling with clearing the subtype value when the Type value changes. Although I can update the drop-down options based on ...

Consistentize Column Titles in Uploaded Excel Spreadsheet

I have a friend who takes customer orders, and these customers are required to submit an excel sheet with specific fields such as item, description, brand, quantity, etc. However, the challenge arises when these sheets do not consistently use the same colu ...

When working in Node, leverage the `then()` method to execute functions sequentially

Is there a way to run a loop function synchronously rather than asynchronously without using callbacks or external libraries? File 1 var db = require('./promiseUnderStanding'); var fun = function () { for (var i = 0; i < 10; i++) { ...

Retrieve the scrolling height in Vue.js 2 window

I need to apply the sticky class to the navbar when a user scrolls down, and remove it when they scroll back up. To achieve this, I am attempting to calculate the scrolled height. Currently, my code looks like: mounted(){ this.setUpRoutes(); wind ...

Get the JSON array by decoding the JSON data in PHP

I have a JavaScript function that creates a JSON array and uses an AJAX post method. How should this JSON array be decoded on the PHP side? Here is my JavaScript function: var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"dat ...

Transferring slot data from Parent components to Child Components

I've created a custom component called async-select based on another component, vue multiselect. Here's how: Check out the code here: https://jsfiddle.net/2x7n4rL6/4/ Although vue-multiselect provides several slots, I want to utilize them withi ...

How can I assign a specific class to certain elements within an *ngFor loop in Angular?

I have a situation where I am utilizing the *ngFor directive to display table data with the help of *ngFor="let record of records". In this scenario, I am looking to assign a custom CSS class to the 'record' based on specific conditions; for exam ...

What is the best approach for preserving server data across all users?

Learning Vue has been quite the journey for me, and I'm stuck on how to properly set up a "global storage". Let's get straight to the point: I need to fetch user data once (from the server) so that it can be accessed from any component. For in ...

Removing a value from a JavaScript object

Looking to delete a specific value from an object with multiple values? This is how my object is structured: { 'how can i change my password?': [ 'how can I change my password?', 'how may I change my password?', ...

In a VueJS project, access an xlsx file stored in the public directory by reading its contents

My current challenge involves trying to extract a quiz template from an xlsx file in order to create the quiz within it. Unfortunately, storing the xlsx file as json in a database is not a feasible solution for me at this time. I experimented with using ...

Creating a calculator with JQuery and encountering challenges with performing multiple calculations

I've been working on a calculator using jQuery, but I'm encountering issues with the clear button not functioning properly after multiple calculations. On top of that, subsequent calculations are producing inaccurate results. I am seeking to enh ...

Using Ember's transitionTo method and setting a controller attribute within a callback

I am working with Ember code to transition to a specific route while also setting controllerAttr1 on 'my.route' Upon transitioning to "my.route" using this.get('router').transitionTo("my.route"), I have set up a callback function that ...

Discovering the identification of a comment in JavaScript

Here is the code snippet I am working with: <a onclick="lel($(this),'212345555')" class="button"> <a onclick="lel($(this),'241214370')" class="button"> <a onclick="lel($(this),'248916550')" class="button"> & ...

I am encountering an issue while developing a JavaScript filtering system

Hey everyone, I need help with coding a filter in JavaScript and I'm running into an error (Uncaught TypeError: todos.forEach is not a function) that I can't figure out. Can someone assist me in resolving this issue? const todoFilter = docume ...

javascript highchart image carousel

I am currently working on a visual chart project using the JavaScript library highchart. After setting up my chart with some dummy data, I am looking to incorporate functionality that allows for triggering an image slide based on the chart data. Specific ...

Craft dynamic SVG components using TypeScript

Looking to generate a correctly formatted SVG element using TypeScript: createSVGElement(tag) { return document.createElementNS("http://www.w3.org/2000/svg", tag); } Encountering an issue with tslint: Error message: 'Forbidden http url in str ...

VueGapi does not perform any actions when attempting to request multiple scopes simultaneously

Here is the Vue3 main.js file that I'm working with: app.use(VueGapi, { apiKey: 'MyApiKey', clientId: 'myClientId.apps.googleusercontent.com', discoveryDocs: ['https://classroom.googleapis.com/$discovery/rest?versi ...

I am experiencing difficulty getting my component to properly implement the bootstrap NavBar and NavIcon styles

I am new to using bootstrap with react and I am facing an issue where the dimensions are not being applied to my Navbar and Navbar Icon. I have already installed dependencies and used className instead of class, but still no changes are visible. import Re ...

Utilize jQuery to extract various input/select box values and compile them into an array for submission using .ajax()

I am currently facing an issue with dynamically generated forms using PHP and updated with jQuery's .appendTo() function as visitors interact with it. My main goal is to collect all input text and select box values from the current form and submit the ...