Why isn't my computed property functioning properly in Vue.js?

Exploring the code snippet provided below:

new Vue({
  el: '#app',
  computed: {
    myMessage: function() {
      return "hello";
    }
  },
  data: {
    message: this.myMessage
  },
  mounted: function() {
    console.log(this.myMessage);
  }
})
<script src="https://unpkg.com/vue"></script>

<div id="app>
  <p>{{ message }}</p>
</div>

https://jsfiddle.net/hk49eL38/

Upon replacing:

this.myMessage with a string (such as "Hello world"), the correct rendering is achieved.

However, when using this.myMessage, the text does not render.

What could be causing this issue?

Answer №1

One issue arises when attempting to assign a computed property as the starting value of the message data property.

During the internal execution of the data function by Vue, the computed properties are not yet processed; this occurs very early on, before the created hook is triggered.

If you attempt to inspect the computed property's value within the beforeCreated hook (the initial life-cycle hook), instead of in the mounted hook as in your example, you will notice that it returns as undefined.

Refer to the component life-cycle for more details:

https://i.sstatic.net/6VExc.png

(*) The diagram has been shortened for conciseness

Computed properties are assessed during the "Init injections & reactivity" phase indicated in the diagram above.

It is not feasible to utilize computed property values as the initial value of a data property; generally, they rely on data property values and other external reactive values (e.g. Vuex getters, Vue router parameters, etc).

Answer №2

It is not necessary to use this before myMessage in VueJS, as the framework already considers everything in the context of this. This is the correct way to structure it:

<script src="https://unpkg.com/vue"></script>

<div id="app">
  <p>{{ myMessage }}</p>
</div>

Answer №3

Ensure that upon component mounting, you assign the value of myMesssage to message.

mounted: function() {
    this.message = this.myMessage
}

Answer №4

Attempt to modify the information in the calculated message

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

Retrieve storage information when an internet connection is unavailable on React Native

One of my recent projects involves creating an application that retrieves data from a URL in the form of an array of objects and then displays this data using FlatList. Upon launching the application, the data is displayed correctly since it's retriev ...

ChartJS is exhibiting an issue within a modal or popup window where the chart is being displayed with a height

I want to show a graph in a modal window when the user clicks a button. The modal is hidden with display: none;, and becomes visible with display: flex; once the button is clicked. If I move the chart outside of the modal, it works without any issues. Ad ...

Enhancing jQuery functionality: Ensuring newly added elements are aware of existing functions

I need assistance with my HTML table. Each row (tr) contains a value, for example 200$, and a delete button. How can I ensure that each new row added automatically knows the recent functions without having to call them every time? $(function () { $(&ap ...

Tips for incorporating external libraries into a Grafana data source plugin

What's the best way to integrate an external library into a Grafana datasource plugin? My plugin is functioning properly, but I encounter an error when trying to use the "mqtt" library that I have installed and added to the package.json file: Plugin ...

Trigger the datepicker's onselect event programmatically

Does anyone know how to manually trigger the onselect event of a datepicker? My code is currently functioning correctly (retrieving data from a database based on the value of the datepicker's altfield), but I'm having an issue where the onselect ...

Updating AngularJS ng-repeat when changes are made to LocalStorage with the use of store.js may not reflect immediately

One of the functionalities I want to implement is displaying a list of items (subject names) that are stored in a LocalStorage element. The code snippet in my view is structured as follows: <div class="list"> <a class="item" href="#" ng-repeat= ...

Experimenting with nested dual dynamic routing within the app's directory

Currently working with NextJS 13 and executing the following operations within the app directory. I am attempting to utilize the generateStaticParams function to generate static pages during build time. The route structure is: subpage/[categoryName]/[gif ...

Only scroll the div if it is not within the visible window

I've been looking at this snippet: The sidebar division is what I'm focusing on right now. I want the div to scroll along as I scroll down the page, but I need it to stop scrolling when its bottom is in view. The same should apply when scrollin ...

Tips for utilizing .env variables within npm scripts

I have set the following variable in my .env file: SHOPIFY_STORE_URL=mystore.myshopify.com Now, I am looking to utilize this variable in an npm script like so: "scripts": { "shopify-login": "shopify login --store=SHOPIFY_STO ...

I encountered a permission denied error while attempting to execute the command npm install -g tsc

My main objective is to convert TypeScript code to JavaScript. However, when I attempted to install the TypeScript compiler globally using 'npm install -g tsc', I encountered the following error: npm ERR! Error: EACCES: permission denied, rename ...

Playing with vue component dependencies

During my attempt to run a unit test, I encountered an error when making an axios call. To handle this error, I successfully mocked the call but faced an issue when trying to utilize an external library dependency (specifically, vue-toasted) to display an ...

Steps for sending data to a modal window

Consider this scenario: I have a function that retrieves some ids, and I utilize the following code to delete the corresponding posts: onClick={() => { Delete(idvalue[i]) }} Nevertheless, I am in need of a modal confirmation before proceeding with the ...

Retrieve information using the request npm package

Currently, I am in the process of developing an application with express js. My approach involves using request(v-2.88.2) to retrieve data from an api. request(url, function(error, request, body) { var data = JSON.parse(body); }); My goal is to utili ...

Can ChatGPT Service Error be resolved?

I tried using chatGPT to help me with my HTML code, but every time I opened it I received an error message saying "Failed to get service" Here is the code that I want to make work: <html> <head></head> <body> <script& ...

Keeping Chart.JS Up to Date: Updating Only Fresh Data

When a button is pressed on my website, a Bootstrap modal containing a Chart.JS is called. The data for this chart is loaded via an Ajax call as shown below: function loadReports(data) { $.ajax({ type: "POST", url: "Default.aspx/getRep ...

Fetch search results dynamically in Wordpress through AJAX

I'm struggling to implement AJAX on my WordPress site to display search results without refreshing the page. Despite trying various solutions found through research, none seem to be working effectively for me. Currently, here is the progress I have ma ...

Error encountered while utilizing MUI Button: Unable to access property 'borderRadius' from an undefined source

import React, { Component } from 'react'; import './App.css'; import Screen from './components/Screen/Screen'; import Button from './components/Button/Button'; import { MuiThemeProvider, createMuiTheme } from 'm ...

Localhost file not refreshing

I'm feeling quite frustrated at the moment. It seems like such a simple issue, but I can't seem to figure it out. I have created a basic webpage with a "tree-view" structure. In my readjson.js file, I am reading from a json file located in json/ ...

JavaScript Firebase: Service worker malfunctioning during navigation

I'm currently developing a website that relies on firebase messaging. To make this happen, a specialized service worker for firebase has been integrated into the site. This website functions as a webchat platform where messages are synchronized and s ...

Attempting to maintain the main navigation highlighted while browsing through the secondary navigation

I am facing a small issue that seems like it should be an easy fix, but I can't seem to figure it out. While working on my site, I'm having trouble keeping the parent navigation highlighted when scrolling through the sub-menu. If you hover over ...