"Vue component inputs fail to update when used in the same instance

I have reused the same component in both the navigation menu and on the people's page.

My problem is that when the SearchComponent inputs in the navigation update their values, the SearchComponent inputs on the people's page do not update, and vice versa. How can I achieve this in Vue JS? Below are my code snippets:

SearchComponent

<template>
  <div class="search">
     <input type="text" v-model="name">
     <input type="text" v-model="email">
     <input type="text" v-model="age">
  </div>
</template>
<script>
export default {
    name: 'SearchComponent',
  data() {
    return {
      name: '',
      email: '',
      age: ''
    }
  }
}
</script>

Navigation

<template>
  <div class="nav">
    <ul>
      <li>Home</li>
      <li>Contact</li>
      <li>About</li>
    </ul>
    <SearchComponent />
  </div>
</template>
<script>
import SearchComponent from './SearchComponent'
export default {
    name: 'NavComponent',
  data() {
    return {
      name: '',
      email: '',
      age: ''
    }
  },
  components: {SearchComponent}
}
</script>

People's Page

<template>
  <div class="persons">
    <SearchComponent />
    <PersonList />
  </div>
</template>
<script>
import SearchComponent from './SearchComponent'
import PersonList from './PersonList'
export default {
    name: 'PersonsPage',
  data() {
    return {
      name: '',
      email: '',
      age: ''
    }
  },
  components: {SearchComponent, PersonList}
}
</script>

Answer №1

Building on what @Eli mentioned, here is a way to ensure that all instances share the same object reference for their data:

<template>
  <div class="people">
    <SearchComponent />
    <PersonList />
  </div>
</template>
<script>
import SearchComponent from './SearchComponent'
import PersonList from './PersonList'
const peopleData = {
      name: '',
      email: '',
      age: ''
    };
export default {
    name: 'PeoplePage',
  data() {
    return peopleData; //Same state object referenced by all instances.
  },
  components: {SearchComponent, PersonList}
}
</script>

Answer №2

Every time a Vue Component is utilized, it generates a fresh instance of itself

Components function as reusable Vue instances, so they accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks. The only exceptions are certain root-specific options like el.

For uniformity across all Instances and to treat them as one component, the data in a component should be declared as an object instead of a function i.e.

data: {
  name: '',
  email: '',
  age: ''
}

Instead of

data: function () {
  return {
   name: '',
  email: '',
  age: ''
  }
}

In your case, you have defined it as:

data() {
return { 
   name: '',
   email: '',
   age: ''
 }
}

You can also explore more about Reusing Components and also How to Organize Components. Since the SearchComponent and PersonList components are children of the Peoples Component, you also need to understand how to pass data from the Parent Component (Peoples) to Child components

Answer №3

Although both instances of the SearchComponent may appear similar, they actually operate independently and have unique data sets. To ensure that they stay in sync, I suggest implementing a global store using Vuex as a centralized source of truth for both components.

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

Inconsistencies with AJAX performance

Hey there, I'm a newbie and absolutely loving this site! Currently diving into the world of JavaScript and have been through numerous tutorials. However, I seem to be struggling with getting Ajax to work. Recently stumbled upon this code snippet on ...

Creating a jQuery multiple image preview feature is a simple and effective way to

Looking to implement a single image upload preview function in jQuery? Want to modify it to allow for multiple image uploads with separate boxes? Check out the HTML script below. <!DOCTYPE html> <html> <head> <title></title> ...

What is the best way to dynamically set the 'selected' attribute in HTML dropdown options using AngularJS data?

I'm currently in the process of developing an angularJS application. Below is a snippet of my PHP code: <label class="item item-input item-select"> <div class="input-label">Do you possess the right to work in the UK?</div> & ...

Adding CSS styles to an HTML page using JavaScript

Unfortunately, I do not have the ability to access the HTML directly as it is generated dynamically by a program. However, I do have access to the JS page that is linked to it. As an example, I am able to manipulate elements using JavaScript like so: ...

Encountering a Hydration Error with Next.JS and MDX-Bundler when a MDX Component Adds Extra New Lines to its Children

Currently, I am incorporating next.js + mdx-bundler into my project. There is a simple component that I frequently use in my mdx files. Everything runs smoothly with the following code: Mdx is a great <Component>format and I like it a lot</Compon ...

Tips for transferring parameters between functions in AngularJS

I'm currently working with the following piece of code: var FACEBOOK = 'facebook'; $scope.handle_credentials = function (network) { hello(network).api('me').then(function (json) { dbService.handle_credential ...

send additional form elements to the AJAX suggestion box script

** shifted to this location: Numerous similar AJAX suggestion boxes without IDs I enlisted the help of a developer to create a jQuery AJAX suggestion box script some time ago, and it has been working flawlessly. Now, I am striving to understand it better ...

Employing promises for retrieving ajax data

I've been struggling to make sure my code waits for an ajax call to finish before proceeding, as I need data in an array first. No matter what I try, it seems like promises might be the best solution in this scenario. Currently, the ajax call still oc ...

Obtain the user's email using nodemailer

I created a contact form using Nodemailer that I am having trouble with. Take a look at the code below: let mailOptions = { from: '<<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e3636360e363636602d2123">[emai ...

What is the best way to execute a JavaScript function using Python Selenium?

Is it possible to repeatedly call the MapITRFtoWgs84() function with input from a text file and save the output to another text file? I believe Selenium might be the right tool for this task. Could you provide guidance on how to achieve this? Attached is ...

Modifying the class of multiple images within an array

I am excited to share my first post here and express my gratitude for all the solutions I have found on this platform. I encountered an issue with using .removeClass and .addClass in my recent program. I am loading multiple pictures into an array called F ...

Animated jQuery carousel with a timer countdown feature

Currently, I am developing a jquery slider/carousel to display various promotions. I am seeking a method to indicate the time left until the next promotion appears. Similar to the flash promo on this website: Do you have any suggestions? ...

What is the reason behind the non-linear execution sequence of JS functions when controlling an sqlite3 database?

In my Node.js application, I have a SQLite3 controller function like this: exports.findUser=function findUser(user){ var temp ; var db = new sqlite3.Database('kitchen.db'); var stmt_user_find = "SELECT * FROM user WHERE un = ?"; db.all(stmt_user ...

Using Choices.js to inject live data into the select dropdown options

I am currently utilizing Choices.js for multi-select functionality and incorporating a select with a search box. Even though I am using Angular.js to populate the data, it does not appear to be functioning correctly. Is there anyone who can assist me in dy ...

Text below a stationary header

I need some help with my code using material-ui-next beta.30. The issue I am facing is that the content within mui.Paper is appearing behind the AppBar instead of below it. Here's my current setup: import * as React from 'react'; import * a ...

Apply express middleware to all routes except for those starting with /api/v1

Is it possible to define a catchall route like this? app.get(/^((?!\/api/v1\/).)*$/, (req, res) => { res.sendFile(path.join(__dirname, '../client/build', 'index.html'));}); ...

Provide details on the final parameters

After creating my discord.js bot, I had the idea to implement a translator feature. To achieve this, I need to extract the last argument from incoming messages. client.on("message", async (message, args) => { if (message.content.startsWith(` ...

What is the best way to send data to my Vue.js component?

I am currently developing a Vue.js repeatable component that enables users to perform multiple tasks, such as entering a question and selecting the answer type from a drop-down menu. The challenge I am facing is related to displaying a specific number of b ...

NodeJS:UncaughtPromiseError

Each time the command npm run start is executed, everything appears to be normal and the logs indicate no issues until encountering the following error: (node:4476) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of und ...

An issue arose while attempting to pin a file on IPFS: A TypeError [ERR_INVALID_ARG_TYPE] was encountered, specifying that the argument "url" must be a string data type

Adding the files to another project resulted in an error that I am struggling to understand. When running "node scripts1/runScript.js", the error message received is as follows: Error occurred while pinning file to IPFS: TypeError [ERR_INVALID_ARG_TYPE]: ...