Why isn't my watch function functioning properly within Vue?

In my JS file, I have two components. The file starts with this line: const EventBus = new Vue();

I am trying to pass two strings, 'username' and 'password', from the first component to the second component, but it's not working. Can you help me identify where I am going wrong?

First Component:


Vue.component('log-reg-modal', {
    data: () => ({
        username: "",
        password: "",
    }),
    watch: {
        username: function(){
            EventBus.$emit('changed_username', this.username);
        },
        password: function(){
            EventBus.$emit('changed_password', this.password);
        },
    }
});

Second Component:


new Vue({
    el: '#app',
    vuetify: new Vuetify(),
    data: () => ({
        username: "",
        password: "",
    }),
    methods: {
        register : function (event) {
            EventBus.$on('changed_username', this.username);
            EventBus.$on('changed_password', this.password);
        }
    }
});

Answer №1

To effectively handle event communication in Vue, consider utilizing the EventBus.$on method within the created lifecycle hook to subscribe to events.

Alternatively, you can opt for the built-in event handlers provided by Vue instead of using the EventBus.

Implementing Event Bus:

const EventBus = new Vue();

const UserProfileModal = {
  template: `
    <div><input v-model="username" placeholder="Username" />
         <input v-model="password" placeholder="Password" /></div>
  `,
  data: () => ({ username: "", password: "" }),
  watch: {
    username: function() { EventBus.$emit("changed_username", this.username) },
    password: function() { EventBus.$emit("changed_password", this.password) },
  }
};

new Vue({
  el: "#app",
  components: { UserProfileModal },
  data: () => ({ username: "", password: "" }),
  created() {
    EventBus.$on("changed_username", val => this.username = val);
    EventBus.$on("changed_password", val => this.password = val);
  }
});

Using 'built-in' this.$emit(..., ...):

const UserProfileModal = {
  template: `
    <div><input v-model="username" placeholder="Username" />
         <input v-model="password" placeholder="Password" /></div>
  `,
  data: () => ({ username: "", password: "" }),
  watch: {
    username: function() { this.$emit("changed_username", this.username) },
    password: function() { this.$emit("changed_password", this.password) },
  }
};

new Vue({
  el: "#app",
  components: { UserProfileModal },
  data: () => ({ username: "", password: "" }),
  methods: {
    handleUsernameChange(val) { this.username = val },
    handlePasswordChange(val) { this.password = val }
  },
});

Answer №2

  1. Functions must be used as handlers in EventBus.$on, not properties themselves.
  2. Before using the log-reg-modal component, have you invoked the register method?

Answer №3

In Vue's lifecycle, it is recommended to place EventBus.$on methods within the created() function.

created (){
        EventBus.$on('changed_username', (data) => {
            this.username = data;
          });
        EventBus.$on('changed_password', (data) => {
            this.password = data;
          });
}

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

A method of submitting by simply pressing the enter key alongside clicking on a Bootstrap button

Here is the HTML code I am using to input prompts into a chatbot: <div class="input-group mb-3"> <input type="text" class="form-control" id="chat-input"> <div class="input-group-append ...

Commitments shatter amidst constructing a website

Utilizing promise and http.get to retrieve data from a JSON API in Wordpress. Once the data is retrieved, it should be displayed on a page... However, an error occurs when attempting to build the page due to the data not being available. What steps can ...

What is the best method for extracting information from this data? (extracting data from

I need assistance. I've written multiple arrays to a text file and now I'm trying to parse them. What am I doing incorrectly? fs.readFile("./data.txt", "utf8", function(error,dataRes){ console.log('Reading data') ...

Error: Unable to execute $(...).stellar since it is not a recognized function

Having some trouble implementing the stellar plugin. I've included all the necessary js, but keep getting an error in the dev tools console: 'Uncaught TypeError: $(...).stellar is not a function'. Here's what I have in the head tags: ...

What is the process for loading a script file from within a component's HTML?

My goal was to include a specific script file in the component html, but I noticed that when I added the script reference within the html itself, the inner script file was not rendered along with the component on the page. Component import { Component } ...

Guidelines for establishing authentic headers on a SignalR connection

Can headers be set on the SignalR connection directly? I am aware of setting query string parameters but it is not secure enough for my specific scenario. var conn = ($ as any).hubConnection(); conn.url = URL; conn.qs = { "token": SECRET_KEY }; conn ...

Design my div layout to resemble a tree shape

Take a look at this URL. I have dynamically created divs in a nested structure for a sports tournament. I need help styling the divs to match the tournament structure. This is how I want my structure to look. The code is functioning properly, it's ju ...

Jquery spinner overlay for enhanced loading experience

Currently, I am incorporating jQuery/Ajax in my project and wanted to include a spinner when an ajax request is made. The specific scenario involves two tabs on the UI: Home and Activities. When the user clicks on the Activities tab, an ajax request is sen ...

Acquire the jQuery cookie with the power of AngularJS

I am currently utilizing jquery.cookie v1.4.1 to set a cookie in the following manner: $.cookie('userCookie', $("#user").val()); The value returned by $("#user").val() is typically something like 'username' Now, within an angular app ...

What is the process for integrating Android Java code with Node.js code?

I have some code that I am trying to integrate with Node.js for Firebase notifications on my Android application. I found a blog post outlining the implementation here: The Node.js code listens to changes in my Firebase Database and triggers notifications ...

Having trouble deciphering mathematical formulas while editing content on ckeditor

While using math formulas in CKEditor, I noticed that when I insert new content via textarea, the formulas are displayed correctly. However, when I go back to edit the content, the text formulas do not display as before. This is the source code I am using ...

Having trouble with Selenium WebDriverJS on both FireFox and Internet Explorer

Having developed multiple JavaScript tests using chromedriver to run them in Chrome, I am now facing the challenge of running these same tests in FireFox and IE. The test below is functional in Chrome: var assert = require('assert'), test = requ ...

How can VueJS manipulate state with Mutation?

I have set up a Vuex Store that returns data on headers and desserts. The desserts object includes a property called display, which is initially set to false. In my project, I am using a component called Row within another component named Table. The Row co ...

What is the method for designating the specific pages on which the stripejs script should be loaded?

The performance of the main-thread is being significantly impacted by Stripe's script, as illustrated in the image provided by Google Insights. https://i.stack.imgur.com/bmdJ2.png My concern is that the page currently experiencing issues does not ac ...

What is the best way to animate my logo using JavaScript so that it scales smoothly just like an image logo

I dedicated a significant amount of time to create a unique and eye-catching logo animation for my website! The logo animation I designed perfectly matches the size of the logo image and can be seamlessly integrated into the site. The issue arises when th ...

Utilize Vue.js to take screenshots on your device

After following the tutorial at https://www.digitalocean.com/community/tutorials/vuejs-screenshot-ui, I was able to successfully capture a screenshot with Vue.js. However, it seems that the dimensions of the screenshot are not quite right. Issue: The cap ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

Set the value of one email input to another email input in AngularJS

I'm having trouble trying to link an email input field to another in angularjs without success. Here is what I have attempted so far: <div class="row-fluid"> <div class="control-group span12"> <label for="email">Email</labe ...

Vue JS sorting elements and reverting back to their original state

Within my Vue application, I have a list of results that I want to sort alphabetically after performing a search. However, I also need the ability to revert back to the original order, which is based on relevancy in my case. The 'relevancy' orde ...

Implementing dynamic component rendering and iterating through a list in React JS based on state changes

Trying out React JS for the first time and encountering a couple of issues. 1) Attempting to display a table from a different class upon clicking the show button. However, even when the state is true for showing the table, it doesn't appear. 2) In t ...