箭头功能
我有一个运行一些D3.js函数的pinia商店。在.on()
函数中,我试图访问this.piniaAction
,而不是this
,这是SVG路径。
例如:
export const useStore= defineStore('myStore', {
actions: {
piniaAction() {
//Some stuff is done here
},
d3Action() {
const svg = d3.select("#id")
const group = svg.append("g")
group.append("rect")
.on("click", function(){
let myRect = d3.select(this) // This correctly gets the scoped svg element
this.piniaAction() //I want this to access the pinia action, not svg element
}
}
}
}
我找不到任何可以帮助我访问.on()
函数范围内的pinia动作的东西。
了解javascript中的this
这是一个复杂的概念
您可以使用arrow function
或set temp variable
来解决这个问题:
箭头功能export const useStore= defineStore('myStore', {
actions: {
piniaAction() {
//Some stuff is done here
},
d3Action() {
const svg = d3.select("#id")
const group = svg.append("g")
group.append("rect")
.on("click", () => {
let myRect = d3.select(this) // This correctly gets the scoped svg element
this.piniaAction() //I want this to access the pinia action, not svg element
}
}
}
}
临时var
export const useStore= defineStore('myStore', {
actions: {
piniaAction() {
//Some stuff is done here
},
d3Action() {
const $this = this
const svg = d3.select("#id")
const group = svg.append("g")
group.append("rect")
.on("click", function(){
let myRect = d3.select(this) // This correctly gets the scoped svg element
$this.piniaAction() //I want this to access the pinia action, not svg element
}
}
}
}
export const useStore= defineStore('myStore', {
actions: {
piniaAction() {
//Some stuff is done here
},
d3Action() {
const svg = d3.select("#id")
const group = svg.append("g")
group.append("rect")
.on("click", () => {
let myRect = d3.select(this) // This correctly gets the scoped svg element
this.piniaAction() //I want this to access the pinia action, not svg element
}
}
}
}
export const useStore= defineStore('myStore', {
actions: {
piniaAction() {
//Some stuff is done here
},
d3Action() {
const $this = this
const svg = d3.select("#id")
const group = svg.append("g")
group.append("rect")
.on("click", function(){
let myRect = d3.select(this) // This correctly gets the scoped svg element
$this.piniaAction() //I want this to access the pinia action, not svg element
}
}
}
}