utilize the vue component data

I have created a basic component, but I am encountering an issue where attempting to access the component's data returns undefined. Here is my code snippet:

Vue.component({
  template:`<div>{{message}}</div>`,
  data() {
     return { comments: [
        {title: 'hello' , message: 'world'},
        {title: 'hellowww' , message: 'worldssss'},
     ]}
  },
  mounted: function() {
      console.log(this.comments) // prints undefined - not working
      console.log(this.$root.comments) // prints undefined - not working
      console.log(comments) // prints undefined - not working
  }

});

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

Answer №1

It's possible that one of the reasons for the issues in your code could be related to how you pasted the question and code:

  • The use of Vue.component did not specify a tag name.
    • I made an adjustment by adding comments-component in
      Vue.component('comments-component', {
      .
  • The component's template (
    template:`<div>{{message}}</div>`
    ) referenced a variable called message which was missing.
    • To resolve this, I included message: "check the console", in the data() section.

After making these changes, the mounted function and this.comments in

mounted: function() {
    console.log(this.comments)
}

should now work as intended.

Feel free to check out the demo below.

Vue.component('comments-component', {
  template:`<div>{{message}}</div>`,
  data() {
     return { 
     message: "check the console",
     comments: [
        {title: 'hello' , message: 'world'},
        {title: 'hellowww' , message: 'worldssss'},
     ]}
  },
  mounted: function() {
      console.log(this.comments)
  }

});

var app = new Vue({
   el: '#root'
});
<script src="https://unpkg.com/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d8aeadbd98eaf6edf6e9eb">[email protected]</a>/dist/vue.min.js"></script>

<div id="root">
<comments-component></comments-component>
</div>

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

Ways to mimic an Angular directive with a required field

Recently, I encountered a challenge that involves two directives: directive-a, directive-b. The issue arises because directive-b has a `require: '^directive-a' field, which complicates unit testing. In my unit tests, I used to compile the direc ...

Ways to ensure the title changer works seamlessly for everyone

Having a title changer for elements visible in the viewport is crucial. However, the current setup only works for a single division and fails to function with multiple divisions. Click Here for Live Testing and Viewing Check out the jsFiddle for Code V ...

Retrieve information from Node.js using Express

I am working on a server with Node.js and using Express to create a web application. I have successfully implemented a function called rss_interrogDB that retrieves an array from a database. Now, I am trying to use this array to display a list on the HTML ...

One way to automatically pass a default date parameter to an AJAX GET call in JavaScript is to set the initial date value before making the request. As the

Upon page load, I want to display the current date's attendance. After selecting a specific date, I aim to fetch and show the details for that selected date. The current issue I am facing: When I search for a particular date, I receive data for bot ...

Disappear solely upon clicking on the menu

Currently, I am working on implementing navigation for menu items. The functionality I want to achieve is that when a user hovers over a menu item, it extends, and when they move the mouse away, it retracts. I have been able to make the menu stay in the ex ...

Sending a parameter value when onClick function is called

Currently, I am learning React JS and facing a challenge with passing parameters (like button ID or tab value) to the Tab onClick event. It appears that I'm receiving 'undefined' results when trying to pass attribute names as parameters. Ple ...

When a user toggles one div, the other toggled div should automatically close

Below is a snippet of code where I have implemented a functionality using vue.js to toggle different divs based on button clicks. The current setup allows for toggling individual divs when their corresponding buttons are clicked. However, I am looking to ...

Issue encountered when implementing promise and await within a Vue method

I've implemented a function in the mounted() hook to fetch files from my Dropbox account using a promise. Once the promise is resolved successfully, I iterate through all the files and execute another promise function to retrieve additional informatio ...

AngularJS encountered an error while attempting to create a module with obfuscated code, resulting in a $injector:

Attempting to obfuscate my angularjs application using mangling is resulting in an error. I have been advised to use ngmin to address this issue. Following this advice, I have successfully used ngmin to properly encapsulate my controller code within an arr ...

Refresh all color pickers with Bootstrap 4 Colorpicker - enforce the update of every color selector

Currently, I am utilizing the Bootstrap 4 color picker library which can be found at this link: In my code, I have defined color pickers that look like this: <div class="input-group cpicker"> <input type="text" class="form-control input-lg" ...

Utilizing ThemeProvider in a Different Component in React

In my App.js file, I have a function that toggles between light and dark mode themes: import { createTheme, ThemeProvider } from '@mui/material/styles' import Button from '@mui/material/Button' import Header from './components/Head ...

Is it possible to utilize the inline/hardcoded type declared in the component.d.ts file for reuse

Is there a way to pass props selectively to the library component? The library has hardcoded multiple values in an inline type. If my code needs to automatically update with any new additions to the library-defined type, can I reuse those inline values r ...

Steps for displaying a website within a specific Div using HTML

I'm trying to set up a website to open within a specific <div> tag, like the example shown in this link: Responsive. Can anyone spot what I'm doing incorrectly? <html> <head> <script> function mobile320() { ...

Exploring the behavior of Object.assign in for loops and forEach loops

I've come across an interesting anomaly with Object.assign in the following scenario. function sampleFunction(index, myList) { myList.forEach((element, i) => { if (i === index) { console.log(Object.assign({}, {"newKey": " ...

How to disable scrolling for React components with CSS styling

When incorporating a React component into my HTML, I follow this pattern: <html> <body> <div id=app>${appHtml}</div> <script src="/bundle.js"></script> </body> </html> Within my application, th ...

What is the best way to utilize jspdf for formatting data, specifically when wanting the first column to be in bold?

How can I customize data formatting using jspdf? Specifically, I would like the first column to be in bold and the second column in normal text. Additionally, I want to align them in the middle of the pdf output with different colors for each column. Belo ...

Enhancing jQuery's ScrollTop Functionality

My jQuery script for scrolling to the top of a container seems to accelerate after it starts. It begins slowly and then speeds up. Is there a way to prevent this lag at the beginning and maintain a consistent speed throughout the entire scroll? // Once t ...

Revamping HTML Label 'for' with JavaScript: Unveiling Effective Techniques

I'm facing an issue with changing the target of a label that is associated with a checkbox using JavaScript. Here's the code I have: <input type="checkbox" id="greatId" name="greatId"> <label id="checkLabel" for="greatId">Check Box&l ...

Displaying various elements with distinct properties in React using ES6

<---------------------MODIFICATION------------------------> I initially thought I needed multiple onChange functions, but after reviewing the answers provided, I discovered a solution thanks to the helpful user's response. With some experimenta ...

Difficulty adapting CSS using JavaScript

I am looking to adjust the padding of my header to give it a sleeker appearance on the page. I attempted to achieve this with the code below, but it seems to have no effect: function openPage() { var i, el = document.getElementById('headbar' ...