Keep an eye out for any updates in the information

I'm currently grappling with the Vue instance concept while utilizing vue-loader and webpack to import a Vue component called Search.

import Vue from 'vue';
import Search from '../Search.vue';
const vm = new Vue({
   el: 'search',
   render: h => h(search)
});

Within the component:

export default {
    data: function() {
        return {
            results: 'current results'
        }
    }
}

I aim to trigger an event from inside the component upon a property change that can be watched from the instance.

An example of using the API should look like this:

vm.$watch('results', function (newVal, oldVal) {
  // do something
})

However, the event is not triggering anything.

I believe my understanding of how to use the Vue instance is lacking since I am also unable to initialize any data in the instance accessible within the component like so:

const vm = new Vue({
   el: 'search',
   data: {index: 1},
   render: h => h(search)
});

The Index is not available within the component for use. How can I resolve this?

Answer №1

If you want to utilize watchers in this scenario, let me guide you through the process of incorporating data into your components effectively. By defining data within Vue instances, you can access them accordingly. However, if you aim to pass this data to your components, you can leverage the functionality of props.

To understand more about this concept, visit: https://v2.vuejs.org/v2/guide/components.html#Props

The key aspect here is having a child component similar to yours...

export default {
  data: function() {
    return {
        results: 'current results'
    }
}

... and you need to make certain values accessible from external sources for use within the component. This can be achieved by specifying the expected input using props, as demonstrated below:

export default {
  props: ['index'],
  data: function() {
    return {
        results: 'current results'
    }
}

Subsequently, you simply have to pass these values to your component when implementing it. For instance, by assigning a name attribute such as name: test-element and storing the component in a file named TestElement.vue (modifiable per your preference).

Following this, import your component into its parent using

import TestElement from './TestElement.vue'
. Accordingly, register the component within your Vue instance utilizing
components: {'test-element': TestElement}
.

This setup enables you to integrate an HTML tag <test-element> in your current file, rendering the specified content from your component seamlessly.

You can then bind values to the prop which will subsequently be passed on to the component like so:

<test-element :index="index"></test-element>

This approach ensures that the value of index originating from the parent Vue instance is transferred to the child component for further utilization, such as calculations or other functionalities within the template.

In terms of watchers, you can implement one within your component using the following method...

export default {
  props: ['index'],
  data: function() {
    return {
      results: 'current results',
      index: this.index // utilizing the prop provided!
    }
  },
  watch: {
    index: function (newValue, oldValue) {
      // perform actions based on the changing value
    }
  }
}

That sums up the essence of it all! Apologies for the lengthiness, but I trust this information serves your needs adequately ;)

Answer №2

After encountering this problem, I found the solution.

const Search = Vue.extend(Search);
const vm = new Search({el: 'search'});

vm.$watch('results', function (newVal, oldVal) {
  // perform a specific action
})

Now, I am able to monitor changes on the properties externally from the .vue file. This had been a challenge due to my combination of .js and precompiled .vue using vue-loader.

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

NodeJS Sequelize is raising an UnhandledPromiseRejectionWarning due to a TypeError with the message "user.destroy is not a function."

I have been following a NodeJs tutorial on YouTube, but I encountered an issue when trying to delete users by id. The code provided in the tutorial worked perfectly, but my implementation seems to be failing. Can someone please review my code and point out ...

What is the best way to retrieve information from a public API when a form is submitted using vanilla JavaScript?

Currently, I am in the process of creating a basic webpage that allows users to input a year in a text field and view a list of F1 races for that specific year. To gather my information, I am using a public API available at . My goal is to accomplish this ...

What is the technique for incorporating FontAwesome icons onto an HTML 5 canvas?

I am encountering an issue while trying to use FontAwesome icons within my HTML 5 canvas. Here is what I have attempted: ct.fillStyle = "black"; ct.font = "20px Font Awesome"; ct.textAlign = "center"; var h = 'F1E2'; ct.fillText(String.fromCha ...

The oddity of a lone quotation mark trying to break

var x = "Test \'" > undefined var y = "Test '" > undefined x === y > true x > "Test '" https://i.stack.imgur.com/ZrHo5.jpg Aha! Both of these strings are actually equal (as shown in the example code) - but why is that the ...

Trigger ng-change event for each dropdown selection made in AngularJS

Currently, I have a dropdown menu that allows users to select a report for generation. When a user picks a report from the dropdown, it generates and downloads the report for mobile viewing. By utilizing ng-change, the system only detects when a user wants ...

VueJS - Validating Props with Objects

What is the best way to validate Object type props in VueJS to guarantee that certain fields are defined within the object? For instance, I need to make sure that the user prop includes 'name', 'birthDate', and other specific fields. ...

Tips for rendering a mustache template on your local machine

I've been attempting to harness the power of mustache and jQuery to import a JSON file and create an HTML template. Despite following tutorials diligently, I'm facing a frustrating issue where nothing appears in the browser and there are no erro ...

Cannot save PDF files to a server using jsPDF

I'm new to this community and still learning javascript & php. I am having trouble saving my PDFs with jsPDF to the local storage on the server (automatically generated). It used to work in the past, but now when I add Canvas (javascript) to my HTML, ...

Having trouble incorporating choreographer-js, an external JavaScript library, into my Nuxt project as it is not functioning correctly

Just starting out with vue.js and nuxt.js, I wanted to experiment with integrating an external JavaScript library into my nuxt.js project. My goal is to test out the functionality provided by this library: The library in question can be found here: https: ...

Is anyone knowledgeable about <?php bp_activity_id() ?> in BuddyPress?

I have been trying to solve this issue over the past few days. Here is an overview of my problem: <?php bp_activity_id() ?> In my BuddyPress gallery plugin, I have 2 comment forms. The first one appears when there are no comments yet and it 'c ...

align image vertically within a floated container

There are 5 floated divs with heights stretched to 100% of the document height using JavaScript. Each of the 5 divs contains an img element. <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> <lin ...

The functionality of returning false on ajax response does not effectively prevent the form from submitting

I'm encountering an issue where the return false statement doesn't seem to work when using an AJAX call. The form is still getting submitted successfully despite trying to prevent it with a conditional check on the response from the AJAX request. ...

Endlessly adding my item to Firebase through the child_added/set feature

Can you assist me in resolving an infinite loop issue I am facing while trying to insert an item into my Firebase through a post form in VueJS? The item keeps getting inserted continuously until I terminate the process. PS : I'm using VueJS ...

Search for objects in the array that have the same name, and then combine the values of those matching

I've done some research on various platforms, but haven't come across a solution to my specific issue. I'm looking to extract objects from an array and group them by their names in order to calculate the total hours for each matching object. ...

Why is "this" not undefined even though I did not bind it in my function's constructor?

When I click my button, it triggers the onClick function below: <button onClick={() => this.onDismiss(item.objectID)} type="button" > The onDismiss function filters a list and updates my React application. Interestingly, I didn't bind th ...

losing track of the requested parameters while working asynchronously with Firestore documents

Today is my first time experimenting with firestore and express. Here is the code snippet I am using: app.post('/api/create', (req, res) => { (async () => { try { console.log(req.body); //the above consle.lo ...

I can't seem to get my JavaScript to connect to my HTML file. What should I do next?

I'm facing a major issue at the moment. My HTML file doesn't seem to be linking properly with my JavaScript file, even though they are located in the same folder. The script link is correctly placed in the HTML file, but for some reason, it just ...

having trouble loading images properly with javascript

I am currently developing an image search program using JavaScript. The program allows users to input a name, and with the help of an XML database, it retrieves images related to that name and displays them on the canvas. However, I have encountered a pro ...

Getting 6 shots to load simultaneously on Jribbble - how can I do it?

Hello! I'm still getting the hang of Javascript, but I've made progress in loading elements onto the page. As a beginner, this is a good start for me. Currently, I am working on a script to load 6 "shots" onto a page, but it seems to be loading ...

Determine the total of the values in an array by adding or subtracting them

I am currently working on a form that contains approximately 50 similar elements organized in a table. Each item in the table consists of three records. The elements are retrieved from the database and displayed in the table using the following code: ...