This is from a child component in Vue.js. I'm trying to pass some data from the parent in sensorData, but the binding isn't happening because the code below uses an arrow function for data. How can I convert this function to a normal function so that the this binding is available.
export default {
name: "SensorChart",
props: ["sensorData"],
data: () => ({
chartOptionsLine: {
xAxis: {
data: ["A","B","C","D","E","F","G"]
},
yAxis: {
type: "value"
},
series: [
{
type: "line",
// data: this.sensorData
data: [910, 423, 61, 752, 262, 3625, 119]
}
],
title: {
text: "Sample Data",
x: "center",
textStyle: {
fontSize: 20
}
},
color: ["#1271c2"]
}
})
};
This worked fine.
export default {
name: "SensorChart",
props: ["sampleData","sampleLabels"],
data: function() {
return {
chartOptionsLine: {
xAxis: {
data: this.sampleLabels
},
yAxis: {
type: "value"
},
series: [
{
type: "line",
data: this.sampleData
}
],
title: {
text: "Sensor Data",
x: "center",
textStyle: {
fontSize: 24
}
},
color: ["#127ac2"]
}
}
}
};
An arrow function expression is a compact alternative to a traditional function expression, but is limited and can't be used in all situations.
There are differences between arrow functions and traditional functions, as well as some limitations:
for more Details in there:
So,if you want to use traditional way, you can use this.
export default {
...
data: function() { return {...} }
}
if you want to use arrow function, While arrow functions do not have their own this pointer, only arguments can be passed when a function is called through call() or apply() (this way can't bind this).