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

What is the proper method for utilizing the "oneOf" keyword in this schema?

Is it possible to have either option A or B, but not both (mutually exclusive)? In Draft 3, I am required to use whatever is available, even though the version on top says 4. This is because when using an array for "required", it throws an error stating t ...

Searching for related values in a nested array of objects using JavaScript: A guide

My goal for this project is to thoroughly examine the path along with all nested elements within the Items and assign them to the details variable. However, due to the limitations of the function inside the useEffect, I am unable to check nested items eff ...

Creating a visual representation of a loading spinner prior to implementing debounce technology

Is there a way to set this.isLoading = true before the debounce function is executed in this method? I'm trying to show a loading spinner while making an asynchronous call with axios. methods: { searchAdminUsers: _.debounce(function(quer ...

Exporting variables in Angular's Ahead of Time (AoT) compiler is

I recently attempted to incorporate dynamic configuration into my project, following a guide I found in this insightful post. While everything functions smoothly with the JiT compiler, I encountered the following error when attempting to build using the A ...

Issue encountered while retrieving the response, in case the node.js server sends the response with a delay

My aim is to upload an image and have the nodeJS server send the path of that image folder back as a response. Unfortunately, when I try sending the response after completing a task, nothing seems to be happening on the angular-side. Below is my componen ...

Tips on effectively transferring formarray to another component

I'm attempting to pass a formarray to a child component in order to display the values within the formarray there. Here is my current code, but I am struggling to figure out how to show the formarray values in the child component. app.component.html ...

Moving information from one controller to another, or the process of converting a controller into a service

Is there a way for me to transfer information from one controller to another? Or can I create a service from a controller? Specifically, I am looking to retrieve coordinates and store them in an object along with other variables. When I try to inject depen ...

Display the output based on checkbox selection using JavaScript

I am working on a feature where I need to capture checkbox inputs using JavaScript and then store them in a PHP database. Each checkbox corresponds to a specific column in the database. If a checkbox is checked, I want to insert its value into the databa ...

Dealing with Javascript exceptions and sending email notifications in Django

I appreciate the traditional method of handling server-side exceptions in Django using Python. I am interested in finding a similar approach for client-side exception handling in JavaScript. So far, I have come across only one option which is DamnIT, but ...

Switching <div></div> to inline-block doesn't seem to have any effect (repl.it provided)

Could someone assist me with changing the div element to an inline block? I've been having trouble with it. For reference, here is my repl.it: https://repl.it/repls/AwareContentTechnician ...

Is it preferred to utilize v-show in combination with v-for?

I understand that using "v-if" with "v-for" is discouraged, but I'm unsure about the case of "v-show" since it simply toggles the display attribute. Here is the code for reference. Essentially, I am trying to switch between 3 different types of fi ...

Creating a table in Javascript using an array of objects

I need a larger version of this data structure. [{ "votes":200, "invalid_votes":140, "valid_votes":60, "voting_section":{"level":2, "zone1":"US", "zone2":"Delaware"} }, { "votes":300, "invalid_votes":40, "valid_votes":260, "voting_section":{"level":3, "zo ...

What are the best tools to develop a browser-based 2D top-down soccer simulation?

I'm looking to create a 2D top-down soccer simulation game for web browsers using modern technologies and without the need for additional plugins like Flash or Silverlight, making it compatible with mobile devices as well. The game will be AI-controll ...

New to Angular: Getting Started with NgModel Binding

Novice query: I am facing an issue with a simple input type=text element linked to ng-model="xyz.zyx", where xyz refers to an object. In my controller, I initialize this object and set the value for the property zyx as shown below: xyz { zyx: $scope.zz ...

Leveraging JavaScript along with the jQuery library and API to showcase information related to

Hey there! I have been working on this API that shows upcoming concerts, but I'm struggling to display the images associated with each concert. I've tried using for loops to iterate through the objects, and it seems like every sixth element has ...

Tips to retrieve an Angular `value` from outside the module

customConfig.js angular.module("steam") .value("customConfig", { baseurl: "http://dev-back1.techgrind.asia/" }); To access the value outside the module, replace the " .." with customConfig.baseurl apiTest.js var frisby = require("frisby"); fris ...

In configuring the print settings, I specified margins to ensure proper formatting. However, I noticed that the margin adjustment only applies to the first page. I need

I have a method that retrieves margin top value from the backend. It works perfectly on the first page of print, but on the second page, the margin top space is missing. initializePrintingSettings() { this.printService.fetchPrintSettings().subscribe(respon ...

Leveraging jQuery to extract the value from a concealed form field

Seeking assistance with a jQuery issue... I am attempting to use jQuery to retrieve the values of hidden fields in a form. The problem I am facing is that there are multiple forms displayed on the same page (result set items for updating), and the jQuery ...

Having trouble getting Emberjs to properly handle an Ajax POST request

Currently, my goal is to send data to the database using Ajax POST. To start off, I have an HTML form as follows: <script type="text/x-handlebars" id="project"> <div class="row"> <div class="span6"> <form class ...

What causes ngClick to stop working following $compile?

http://plnkr.co/edit/kL2uLPQu2vHHKIvRuLPp?p=preview Upon button click, the controller calls a service to compile HTML and inject it into the body. The compiled HTML (displaying "Hello World" from $scope.name) is referring to the scope of the controller, ...