如何确定vuejs中svg的getTotalLength()结果的计时?
此.$refs.pathID.getTotalLength应返回长度时返回0,应返回0时返回长度 我的vue组件是一个svg路径元素,有一个按钮可以切换路径。切换是通过将路径的d attAttribute绑定到名为path的属性来完成的。有一个在mount上运行的函数生成d属性的值,我将该值设置为名为pathValue的属性。因此,如果单击==true,则路径=路径值,否则路径=null。这正如预期的那样有效 此外,我观察path,以便在发生更改时,onclick应该重新计算路径长度,并将其值设置为css自定义变量如何确定vuejs中svg的getTotalLength()结果的计时?,svg,vue.js,Svg,Vue.js,此.$refs.pathID.getTotalLength应返回长度时返回0,应返回0时返回长度 我的vue组件是一个svg路径元素,有一个按钮可以切换路径。切换是通过将路径的d attAttribute绑定到名为path的属性来完成的。有一个在mount上运行的函数生成d属性的值,我将该值设置为名为pathValue的属性。因此,如果单击==true,则路径=路径值,否则路径=null。这正如预期的那样有效 此外,我观察path,以便在发生更改时,onclick应该重新计算路径长度,并将其值设
<template>
<main>
<svg viewBox="0 0 415 200">
<path ref="pathID" :d=path />
</svg>
<button @click="show()">nsr</button>
</main>
</template>
<script>
export default {
data() {
return {
path: null,
clicked: true,
pathValue: null,
pathLength: 0
}
},
methods: {
show() {
if(this.clicked) {
this.path = this.pathValue
this.clicked = !this.clicked
} else {
this.path = null
this.clicked = !this.clicked
}
},
generatePath() {
// generates a string value for the d-attribute were binding to path
let path = "M410 100,"
for(let i = 0; i < 5; i++) {
path += `
h-10,
q-5 -20, -10 0,
h-10,
s-5 -100, -10 -0,
s-5 50, -10 0,
h-10,
q-10 -20, -20 0,
h-5`
}
return path
}
},
mounted() {
this.pathValue = this.generatePath()
},
watch: {
path: function() {
// trigger computed setter here when path is changed onclick
this.calculatePathLength = this.$refs.pathID
},
pathLength: function() {
// set custom variable here
this.$refs.pathID.style.setProperty("--path-length", this.calculatePathLength)
console.log('value of computed property: ' + this.calculatePathLength)
}
},
computed: {
calculatePathLength: {
get: function() {
return this.pathLength
},
set: function(x) {
this.pathLength = x.getTotalLength()
console.log('path length is: ' + this.pathLength)
}
}
}
}
</script>
因此,当单击按钮时,应该更新d属性的值,观察者应该注意路径中的更改,调用计算属性calculatePathLength的setter,更新pathLength的值,然后pathLength的观察者应该在设置自定义属性var path length时调用getter
因此,预期的结果应该是记录路径长度,它是。但是当它应该是非零时,它是零,当它应该是零时,它是非零这个问题在vue论坛上得到了回答,解释是svg没有足够的时间在测量路径长度之前进行更新,这就是vue的目的。$nextTick。以下是修复上述情况的代码:
watch: {
path() {
this.$nextTick(() => this.pathLength = this.$refs.pathID.getTotalLength());
}
},
当您更改此路径时,感谢@wildhart。在计算新的getTotalLength之前,您需要给svg元素重新绘制的时间
Vue提供的功能正是为此目的。要使上述代码正常工作,请执行以下操作:
观察:{
路径:函数{
//单击更改路径时在此触发计算设置程序
this.$nextTick=>this.calculatePathLength=this.$refs.pathID;
},
...