Vue child component not displaying updates after property is cleared (utilizing Vue.js 3 without any bundler)

Currently, I am diving into learning vue.js version 3.0 and I'm in the process of experimenting with child components without using a build system for Vue.

In my project, I pass an array to the child component and then clear it within that component. However, I've noticed that the length change of the array is not being reflected in the HTML as expected. Ideally, I was anticipating the array length to reset back to zero.

If anyone has any insights or suggestions on how to address this issue, I would greatly appreciate it!

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
</head>
<body>
    <div id="app">
          <input type="button" v-on:click="LoadBoundaryList();" value="Add names" />
          <test-component :names=userBoundaries></test-component>
     </div>
    <script>
        const TestComponent = {
            props: ['names'],
            template: `<div>{{names.length}}</div><input type="button" value="remove" v-on:click="removeAllNames()"/>`,
            methods: {
                removeAllNames() {
                    this.names = [];
                }
            }
        }
        const RootComponent = {
            data() {
                return {
                    searchQuery: null,
                    userBoundaries: []
                }
            },

            components: {
              TestComponent
            },
            methods: {
                LoadBoundaryList () {
                    for (var i = 0; i < 14; i++) {
                        this.userBoundaries.push("BoundaryName");
                    }
               },
            }
        }
        var appRoot = Vue.createApp(RootComponent);
        appRoot.mount('#app');
    </script>
</body>
</html>

Answer №1

To update the parent component and remove the list of user boundaries, you must trigger an event using emit, as the list of names is dependent on it.

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta charset="utf-8" />
    <script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
</head>
<body>
    <div id="app">
          <input type="button" v-on:click="LoadBoundaryList();" value="Add names" />
          <test-component :names="userBoundaries" @remove="remove"></test-component>
     </div>
    <script>
        const TestComponent = {
            props: ['names'],
            template: `<div>{{names.length}}</div><input type="button" value="remove" v-on:click="removeAllNames()"/>`,
            methods: {
                removeAllNames() {
                    this.$emit('remove')
                }
            }
        }
        const RootComponent = {
            data() {
                return {
                    searchQuery: null,
                    userBoundaries: []
                }
            },

            components: {
              TestComponent
            },
            methods: {
                LoadBoundaryList () {
                    for (var i = 0; i < 14; i++) {
                        this.userBoundaries.push("BoundaryName");
                    }
               },
               remove() {
                 this.userBoundaries = []
               }
            }
        }
        var appRoot = Vue.createApp(RootComponent);
        appRoot.mount('#app');
    </script>
</body>
</html>

Answer №2

To remove data bound to the parent, utilize emit in the child component:

<html>

<head>
  <title></title>
  <meta charset="utf-8" />
  <script src="https://unpkg.com/vue@next/dist/vue.global.prod.js"></script>
</head>

<body>
  <div id="app">
    <input type="button" v-on:click="LoadBoundaryList();" value="Add names" />
    <test-component :names=userBoundaries @clear="clearNames"></test-component>
  </div>
  <script>
    const TestComponent = {
      props: ['names'],
      template: `<div>{{names.length}}</div><input type="button" value="remove" v-on:click="removeAllNames()"/>`,
      methods: {
        removeAllNames() {
          this.$emit('clear',[])
        }
      }
    }
    const RootComponent = {
      data() {
        return {
          searchQuery: null,
          userBoundaries: []
        }
      },

      components: {
        TestComponent
      },
      methods: {
        LoadBoundaryList() {
          for (var i = 0; i < 14; i++) {
            this.userBoundaries.push("BoundaryName");
          }
        },
        clearNames(arr){
          this.userBoundaries=arr
        }
      }
    }
    var appRoot = Vue.createApp(RootComponent);
    appRoot.mount('#app');
  </script>
</body>

</html>

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

Implementing JavaScript to add a loading spinner to a specific cell

Currently, I'm utilizing the code below (not my original) in order to load an image into a css element (referred to as cell) and showcase an activity indicator. var cell = document.createElement('li'); cell.textContent = this.labelForIndex( ...

Unlock the Power of Heroku: Leveraging Node.js to Share Environment Variables Across JavaScript Pages

Currently, I am following the 'getting started' guide on the Heroku webpage. As part of this process, I have cloned their tutorial repository and decided to add my own index.html and app.js files to the existing /public folder. The directory str ...

Retrieving the UTC offset value from a timestamp string in Node.js/JavaScript

Having a local timestamp presented as a string in the format shown below: '2020-05-19T15:45:07.2306062+05:30' I am trying to figure out how to extract the UTC offset value from this specific date string using nodejs/javascript. Any assistance w ...

I am looking to enhance the dimensions of my shapes by utilizing the ExtrudeGeometry feature in Three.js. Can anyone provide guidance on

I am currently utilizing three.js to create a line in my project. However, I am facing an issue where the line appears flat like a paper, instead of a three-dimensional wall. I am struggling to increase the height of the line in my code. Below is the code ...

The header row in HTML tables sometimes vanishes unexpectedly after sorting the table

Upon filtering the table, I noticed that the header disappears sporadically. The issue is that the table header row should remain in place regardless of whether or not the characters used for filtering are present in the table rows. In Example 1: When fil ...

Error injecting angular.bootstrap in Angular 1.6.5 version

I have a MeanJS.org skeleton app that I've transformed into hapi-js from express, switched to postgres from mongo, and incorporated OAUTH for authentication (mainly because I liked the server/client module folder structure - haha). Everything seems t ...

Tips for managing blur events to execute personalized logic within Formik

I am currently delving into the world of React/Next.js, Formik, and Yup. My goal is to make an API call to the database upon blurring out of an input field. This call will fetch some data, perform database-level validation, and populate the next input fiel ...

Transform a JavaScript time stamp by appending a time zone offset (+0800) to the end

Upon receiving a timestamp in the format of "2019-08-31T00:00:00+0800", I attempted to convert it into a date using JavaScript. However, the result was Fri, 30 Aug 2019 16:00:00 GMT instead of the desired date of 31 Aug 2019. I observed that there is a +0 ...

Add a new element to the page with a smooth fade-in animation using jQuery

var content = "<div id='blah'>Hello stuff here</div>" $("#mycontent").append(content).fadeIn(999); Unfortunately, the desired effect is not achieved with this code. I am trying to create a sleek animation when adding new content. ...

Learn how to efficiently import data into d3.js from several JavaScript arrays, and create a dynamically updating chart without the need to refresh the page

I currently have two arrays: one is a list of numbers called nums, and the other is a list of strings titled places. For example: nums=[1,2,3,4,5] places = ["house","gym", "work", "school", "park"] Both arrays are the same length. I am looking to crea ...

Is there a way to retrieve the ref value from another component file?

Below is the code found in App.vue: <script setup> import Nav from "./components/Nav.vue"; </script> <template> <Nav/> </template> ................................................................... Now, take a ...

The information sent via POST (via fetch JavaScript with PHP8) is not being received by PHP8

My PHP8 server is not receiving the data I am sending. When trying to insert a new song into my API, an error occurs and in the console, I see an object with POST as an empty array. fetch("http://localhost/api.audio-player/",{ method: 'POST&apos ...

Guide on saving the highest score in a game using JavaScript with an if statement

I am currently working on a practice game that involves counting the number of taps made within 3 seconds. I've completed everything except for implementing the functionality to save the high score and display the previous best score if there isn&apos ...

Utilizing asynchronous operations in MongoDB with the help of Express

Creating a mobile application utilizing MongoDB and express.js with the Node.js MongoDB driver (opting for this driver over Mongoose for enhanced performance). I am aiming to incorporate asynchronous functions as a more sophisticated solution for handling ...

AngularJS Services and Factories that are loaded at startup rather than on-demand

Having an issue with my AngularJS application. I have defined some factories that are injected into controllers as needed. The problem is that these factories are initialized when the application first starts up. One problematic service is: PlanningPoker ...

Error encountered when using Vue's conditional rendering in conjunction with conditional statements

Currently, I am in the process of learning Vue and facing some challenges with conditional rendering. Although it is not causing any disruptions to the app's functionality, I keep encountering a console error. At the beginning, the character object i ...

Refreshing and reloading within the same jQuery function

My PHP application involves the use of 2 PHP files. chart.php - This page includes a Google chart. <div id="chart_div" style="height:100%;width:100%"> </div> <script type="text/javascript"> google.charts.load('current', ...

Can you show me a way to display a dynamically created array component on an Angular2 template html?

One way I've been able to generate dynamic component instances is by choosing from pre-existing components. For instance, @Component({ selector: 'dynamic-component', template: `<div #container><ng-content></ng-conten ...

Having issues with a drop-down in Bootstrap. Is there anyone who can assist in getting it to function

I recently implemented a drop-down menu on the top navigation of my website. However, after applying Bootstrap to one of my pages, the drop-down menu stopped functioning properly. Below is the code that was applied: <link href="https://cdn.jsd ...

Unable to display Apexcharts bar chart in Vue.js application

Struggling to incorporate Apexcharts into my Vue.js site, but unfortunately, the chart isn't appearing as expected. -For more guidance on Apexcharts, check out their documentation Here HTML <div class="section sec2"> <div id="chart" ...