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"]
}
})
};
CodePudding user response:
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"]
}
}
}
};
CodePudding user response:
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:
- Arrow functions don't have their own bindings to this, arguments or super, and should not be used as methods.
- Arrow functions don't have access to the new.target keyword.
- Arrow functions aren't suitable for call, apply and bind methods, which generally rely on establishing a scope.
- Arrow functions cannot be used as constructors.
- Arrow functions cannot use yield, within its body.
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).