Updating Vue.js Component Data

I have set up a basic Example Component which is bound to a Vue Instance as shown below:

<template>
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-8 col-md-offset-2">
                <div class="panel panel-default">
                    <div class="panel-heading">Example Component</div>

                    <div class="panel-body">
                        {{ msg }}
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
    export default {
        data : function(){
            return{
                msg : "Hello"
            }
        },
        mounted() {
            console.log('Component mounted.')
        }
    }
</script>

Here is my app.js file

/**
 * First we will load all of this project's JavaScript dependencies including
 * Vue and other libraries. This serves as a great kickoff point for developing
 * powerful web applications using Vue and Laravel.
 */

require('./bootstrap');

window.Vue = require('vue');

/**
 * Next, we will create a new Vue application instance and connect it to
 * the page. You can then start adding components to this application
 * or customize the JavaScript scaffolding to meet your specific requirements.
 */

Vue.component('example-component', require('./components/ExampleComponent.vue'));

var firstComponent = new Vue({
    el: '#app'
});

This is my HTML

<!doctype html>
<html lang="{{ app()->getLocale() }}">
    <head>
        <meta charset="utf-8">
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>


    </head>
    <body>

        <div id="app">
            <example-component></example-component>
        </div>

        <script src="{{ asset('js/app.js') }}"></script>
    </body>
</html>

How can I change the value of msg now? There is no reference to that component anywhere. How should I proceed?

Can this be done?

var ex = Vue.component('example-component', require('./components/ExampleComponent.vue'));
ex.data = "new Value";

Answer №1

Include a props property in your component and assign the msg property to it:

<script>
export default {
     props:{
         msg:{
            type:String,
            default:"Hello"
          }
       },
    data : function(){

    },
    mounted() {
        console.log('Component mounted.')
    }
  }
</script>

Then use it like this:

 <example-component msg="new Hello"></example-component>

UPDATE

If you need to access the child component directly, consider using child component ref

const ExampleComponent = Vue.component('example-component', {
  template: `
    <div>
      <h2>Example component</h2>
      <div>{{msg}}</div>
    </div>
  `,
  data() {
    return {
      msg: "Hello"
    }
  }
});

window.root = new Vue({
  el: '#app',
  components: {
    ExampleComponent
  }
});

root.$refs.example.msg = "new hello"
<!DOCTYPE html>
<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8>
  <title></title>
  <script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5b3b0a085f7ebf0ebf4f2">[email protected]</a>/dist/vue.js></script>

</head>

<body>

  <div id="app">
    <h2>Parent</h2>

    <example-component ref="example"></example-component>
  </div>
</body>

</html>

Answer №2

TL;DR Check out this example, it does exactly what you need: https://codesandbox.io/s/88ojwpjq88

You must differentiate between the component's private `data` and the `props` (data passed to the child component). Refer to this section of the Vue.js guide: https://v2.vuejs.org/v2/guide/components.html

In your component, make sure to declare the prop:

export default {
    props : ['msg'],
    mounted() {
        console.log('Component mounted.')
    }
}

Then you can assign data to the child component like so:

<example-component :msg="myMessage"></example-component>
, assuming that the parent component has declared `myMessage` like this:

data : function(){
   return {
    myMessage : "Hello"
  }
}

To update the value, you can bind it to an input element. Here's an example with a text field:

<input v-model="myMessage">
.

If you type something into this field, you should see the bound value in your component update accordingly.

Please refer to the manual here: https://v2.vuejs.org/v2/guide/index.html. It provides comprehensive coverage for your questions.

Answer №3

To establish communication between parent and child components in Vue.js, you need to add a property to your component and bind it accordingly. Depending on the data flow direction - from parent to child or vice versa - you will either pass data through props or emit events. More information here

When passing data from parent to child:

<template>
  <div> {{msg}} </div>
</template>

<script>
export default {
 props: {
  msg: {
  type: String,
  default: 'Hello'
  }
 }
}
</script>

In the child component:

<template>
 <div>
  <parent :msg="valueMsg"/>
 </div>
</template>

And in the child component script:

<script>
import pai from './pai'
export default {components: {parent},
 data: () => ({
  valueMsg = 'Hello Test'
  })
}

Check out this example for reference

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

Send an AJAX request to redirect to a different page on a PHP server

After collecting data from JavaScript, my page transfers it to PHP and then MySQL. The issue arises when I want the page to redirect to different pages based on the database content. I attempted to use the header function, but it only displayed the entire ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...

Is there a way for me to delay sending an immediate response until the asynchronous loop has completed?

Currently trying to implement something similar to the code snippet below. I suspect that the issue lies within the asynchronous call as it seems like the response I am getting is always an empty array, despite the API returning data. As a beginner in th ...

Error message: Act must be used when rendering components with React Testing Library

I am facing difficulty while using react-testing-library to test a toggle component. Upon clicking an icon (which is wrapped in a button component), I expect the text to switch from 'verified' to 'unverified'. Additionally, a function ...

Troubleshooting a Blank Screen Issue when Deploying React and Ruby on Rails on Heroku

My Heroku test environment features a Ruby on Rails backend and React frontend combination. After pushing out some changes, the test environment is now displaying either a blank screen with a JavaScript error message or another error related to certain p ...

Encountered an issue while installing npm dependencies for webtorrent: "Error: Unable to locate 'fs' - Fountain-Js (Yeoman)"

Having trouble installing an NPM dependency in my code. Successfully installed the module using this command: npm install --save webtorrent This is the content of my package.json file: ./package.json { "dependencies": { "angular": "^1.5.0" ...

What could be causing the issue with updating a js file using ajax?

I've been dealing with a php file called users. Initially, everything was going smoothly as I wrote some JavaScript code for it. However, after making updates to the JavaScript code, it seems to have stopped functioning. Below is the content of the p ...

Guide to adding files to a WordPress post with Selenium in Python

I attempted to automate the creation of WordPress post content using Selenium Webdriver (Python), but I encountered an issue with uploading files in the post content. Despite searching for a solution, most methods involved send_keys which is not suitable f ...

Use ng-class in a P tag to assess a variety of expressions

Is there a way to apply ng-class to automatically evaluate negative values within a < p > tag? <p <strong>LW$:</strong> {{d.lw_metric}} <strong>LW:</strong> {{d.lw_metric_percentage}} <strong>L4W:</strong> {{d.l ...

No styles are appearing on a specific element after running a specific jQuery function on that element within a Vue page

I recently integrated JQuery-AsRange (https://github.com/thecreation/jquery-asRange) into my vue.js project. Everything functions as expected within the .vue page, however, I am facing an issue with css styling not being applied. The css styles should be ...

Is there a similar feature to RxJs version 4's ofArrayChanges in RxJs version 5?

Currently utilizing Angular2 and attempting to monitor changes in an array. The issue lies with only having RxJs5 available, which appears to lack this specific functionality. ...

Conflicting styles arise when using the makeStyles function from Material UI with imported

In working on a React component library using create-react-library, I have incorporated basic components that utilize Material UI components and the material UI hook-based styles pattern. For example (in a simplified form): // LibraryComponent.js const u ...

Issue encountered when attempting to install Vue-cli due to error with the chalk

Issue with VUE-CLI configuration: internal/modules/cjs/loader.js:596 throw err; ^ Error: 'chalk' module not found at Function.Module._resolveFilename (internal/modules/cjs/loader.js:594:15) at Function.Module._load (internal/modu ...

Tips for implementing filters in Angular2 without using the package field in the console

I am currently experiencing an issue with a filter field in my code. The filter works fine when all the package data is present, however, some items do not have a package field. As a result, I need to filter based on the package name but I am encountering ...

Retrieve recently appended DOM elements following the invocation of createComponent on a ViewContainerRef

I have a current function in my code that dynamically creates components and then generates a table of contents once the components are added to the DOM. This service retrieves all h3 elements from the DOM to include in the table of contents: generateDy ...

Having trouble resolving errors in Visual Studio Code after failing to properly close a parent function? Learn how to fix this issue

Here we have the code starting with the construct function followed by the parents function public construct() //child { super.construct; } protected construct() //parent { } The issue arises where I am not receiving an er ...

What is the best way to generate multiple progress bars by leveraging a for loop?

Exploring the code snippet below, I've been creating a progress bar that reacts to specific data input in array form. However, the issue I've encountered is that the code only generates a single progress bar. How can I incorporate this into my f ...

Determine the moment at which the input is altered by adjusting the slider

I'm encountering an issue with making this work. My goal is to calculate input bmi_val whenever one of the other 2 inputs is modified. These inputs can be changed either directly by the user (entering a value into one of them) or through a jQuery sli ...

Issue with Laravel 7 Auth functionality not functioning properly on live website

When attempting to deploy a Laravel site to Bluehost, I encountered an issue where successful login should redirect to '/home' but instead redirects to '/login'. This behavior is not present when running the same code on localhost with ...

Errors encountered in the ajax request, specifically 404 and 401 errors

Using jQuery's ajax method, I am submitting an ajax request in the following manner: $.ajax({ type: "PUT", url: specifiedURL, contentType: "application/json", data: JSON.stringify(data), dataType: "json" ...