What is preventing me from accessing my data function within my computed property?

I have a piece of code that looks like this:

 data() {
    return {
      hello: "hello",
   }
}

Additionally, I have created a computed property as shown below:

computed: {
    serviceHello() {
      return {
        sayHello() {
          console.log(this.hello);
        },
        sayHi(){
          console.log("hi");
        }
    }
}

Upon calling my computed properties in the mounted hook like this:

this.serviceHello.sayHello(); // Output : undefined
this.serviceHello.sayHi(); // Output: "hi" 

However, when I checked what is inside this, it only displayed the content from the computed properties (sayHello and sayHi) without access to the values in my data. My goal is to find a way to access the data from within my computed properties. Specifically, I want sayHello to display the value stored in hello from my data.

Answer №1

To utilize the value of this globally, simply assign it to a global variable and then access it within the returned function:

new Vue({
  el: "#app",
  data() {
    return {
      message: 'Welcome to Vue !',
    };
  },
  computed: {
    serviceHello() {
      let vm = this //assign to global variable vm
      return {
        sayHello() {
          console.log(vm.message);//access using vm
        },
        sayHi() {
          console.log("hi");
        }
      }
    },
  },
  methods: {
    doSomething() {
      this.serviceHello.sayHello();
      this.serviceHello.sayHi();
    }
  },
  mounted(){
   this.serviceHello.sayHello();
      this.serviceHello.sayHi();
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">

  <h1>{{ message }}</h1>

  <button @click="doSomething">Say hello.</button>
</div>

This approach works correctly, although ideally computed properties should be used for returning values based on other properties. It's not their primary job to store functions.

Answer №2

There's an issue with your computed functions. The correct format should be:

computed: {
    sayHello() {
      console.log(this.hello);
    },
    sayHi() {
      console.log("hi");
    }
}

The way you have written it will cause the keyword this to reference the object context instead of the component context.

Answer №3

You seem to be using computed properties incorrectly. In Vue.js, computed properties must always return a value.

Here's the correct way to implement computed properties:

computed: {
  sayHello() {
    return this.hello;
  },
  sayHi() {
    return "hi";
  }
}

You can access these computed properties as `this.sayHello` or `{{sayHello}}` in your templates.

If you need to use a computed Setter, refer to the example below:

computed: {
  fullName: {
    // getter
    get: function () {
      return this.firstName + ' ' + this.lastName
    },
    // setter
    set: function (newValue) {
      var names = newValue.split(' ')
      this.firstName = names[0]
      this.lastName = names[names.length - 1]
    }
  }
}

For more information on computed properties, visit https://v2.vuejs.org/v2/guide/computed.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

JS Concealing all categories on the page

Working on a webpage, I have created a new view to display categories and devised a solution for categorizing all the data in the app. However, I am facing some unresolved issues. The problem lies in the fact that when I first open my webpage, all the ca ...

Is it possible to render the v-for value dynamically?

I have a dynamic component and I'm trying to iterate through different objects from it. However, my current code isn't working as intended. Can someone please guide me on how to make the activeQuestion value in v-for dynamic? Thank you for your a ...

Integrate Arduino's capabilities with Johnny-Five within an HTML JavaScript document

As a beginner in the world of JavaScript, I set out to embark on a project involving turning on a connected LED on an Arduino board by simply pressing a button on an HTML page. After doing some research, I came across a JavaScript library called "johnny- ...

Sort ng-repeat based on the initial character

Working in AngularJS, I am handling an array of objects and aiming to display filtered data based on the first letter. My initial method used was as follows. HTML: <p ng-repeat="film in filmList | startsWith:'C':'title'">{{film. ...

Encountering an 'error' event during installation of the Meteorite router package with the command 'mrt add router'

Encountering an issue with mrt add router, I am receiving the following exception/error message: events.js:74 throw TypeError('Uncaught, unspecified "error" event.'); ^ TypeError: Uncaught, unspecified "error" event. at ...

Can the start and stop times of the typed.js plugin be controlled for typing text?

The typed.js jQuery plugin creates the illusion of text being automatically typed on screen by a robot. Despite researching the resources related to this plugin, I have not come across any information on how to control the starting and stopping of the typi ...

Requesting data with Ajax: utilizing parameters in the format of x-www-form-urlencoded

When adding parameters to a get/post request, it is important to encode them in application/x-www-form-urlencoded form. Is it necessary to encode values each time? Does JavaScript provide a method for encoding values? What options are available for caching ...

Is there a way to send the image's name as a parameter?

I am facing a challenge in achieving a specific task and need some guidance. My current approach involves passing the image name as a parameter to the cancelimage.php script, but it seems like I am not utilizing the variable 'image_file_name' cor ...

Unable to remove click event from nested <li> element

I have a function that enables the expansion and collapse of an unordered list by clicking on the list item. However, the issue arises when the lowest level LI contains a table with a checkbox, as clicking on the table triggers the display of the parent li ...

What is the process for converting a string into a map?

Trying to transform a string from this format: string = "John:31,Miranda:28" To this format: obj = { "John" => 31, "Miranda" => 28 } I attempted to do the following: const class = new Map(); array = string.split(","); However, after splitting t ...

Ensuring secure communication with PHP web service functions using Ajax jQuery, implementing authentication measures

jQuery.ajax({ type: "POST", url: 'your_custom_address.php', dataType: 'json', data: {functionname: 'subtract', arguments: [3, 2]}, success: function (obj, textstatus) { if( !('error' in obj) ) { ...

Guide on creating a cookie verification process with no contents

Request for Assistance: let cartHelper = { cartCookieName: "_cart", getCart: function (callback = undefined) { return apiHelper.getRequest( "/carts", (response) => { documen ...

The issue with 'DemoCtrl' defined in Angular JS is that it does not correspond to a valid argument

signup.html <div ng-controller="UniqueCtrl" layout="column" ng-cloak="" class="md-inline-form inputdemoBasicUsage" ng-app="inputBasicDemo"> <md-content md-theme="docs-dark" layout-gt-sm="row" layout-padding=""> <div> <md- ...

Is there a way to modify the color scheme of the hamburger icon

I'm experiencing difficulties changing the color of a hamburger icon. I've searched for the specific code responsible for the color change, but I haven't been able to locate it. Ideally, I want the color to be white, but on small screens, i ...

Can you explain the significance of foo === +bar?

Currently, I am diving into the world of express and came across a coding challenge that involves downloading a zip file and performing certain tasks. While going through the code, there is a specific line that is causing confusion: const recipe = recipes ...

Improving Array Elements in Vue.js

I have a dataset that starts with the following default structure: summaries: [{client:'', type: '', mention: '', action: '', comment: '', button: true}], There is a button that allows me to add the same ...

How come TypeScript remains silent when it comes to interface violations caused by Object.create?

type Foo = { x: number; }; function g(): Foo { return {}; // Fails type-check // Property 'x' is missing in type '{}' but required in type 'Foo'. } function f(): Foo { return Object.create({}); // Passes! } functio ...

Experiment with utilizing dynamic imports within the useEffect hook

I've been working on testing a custom hook I developed that involves dynamically importing @vimeo/player. The key snippet from the useVideoPlayer hook is as follows: useEffect(() => { async function setup() { const { default ...

Remain on the React page following an HTTP POST request to Flask

Is there a way to stay on the React frontend (localhost 3000) after completing a POST request to a Flask backend from a React form, without redirecting in the Flask backend? Relevant code: export const DateForm = () => { return ( <div&g ...

Encountered an error while trying to retrieve data from

Having trouble with file uploads to the S3 bucket using @aws-sdk/client-s3 library and encountering errors when uploading files larger than 70kbps: `TypeError: Failed to fetch at FetchHttpHandler.handle (fetch-http-handler.js:56:13) at PutObjectCommand ...