I have this in my data :
data() {
return {
hello: "hello",
}
}
And I have a computed property like this :
computed: {
serviceHello() {
return {
sayHello() {
console.log(this.hello);
},
sayHi(){
console.log("hi");
}
}
}
When I'm calling my computed properties like this in my mounted.
this.serviceHello.sayHello(); // console : undefined
this.serviceHello.sayHi(); //console write "hi"
So I tried to see what is inside this but there's only the content from the computed(sayHello and sayHi), I can't access to my values in my data.
My question is, how can I access to the data from my computed ? I want the sayHello to display the hello from my data.
Your computed functions are wrong. It should be:
computed: {
sayHello() {
console.log(this.hello);
},
sayHi() {
console.log("hi");
}
}
The way you have wrote it means that the keyword this will be referencing to the object context itself and not to the context of the component.
You are using the wrong way a computed property. Computed properties must return a value;
Try this way.
computed: {
sayHello() {
return this.hello;
},
sayHi() {
return "hi";
}
}
and access as this.sayHello or {{sayHello}} in templates.
If you are trying to use a computed Setter you can use as this 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]
}
}
}
More infor here https://v2.vuejs.org/v2/guide/computed.html
Just assign this to a global variable and use inside the returned function :
new Vue({
el: "#app",
data() {
return {
message: 'Welcome to Vue !',
};
},
computed: {
serviceHello() {
let vm = this //assign it here to a global variable vm
return {
sayHello() {
console.log(vm.message);//use vm here
},
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 works fine but it's not the job of the computed property which should be used to return some stuff based on other properties