[英]how to fix timing of result for getTotalLength() of svg in vuejs?
this.$refs.pathID.getTotalLength()
在應該返回長度時返回0
,在應該返回0
時返回長度。
我的 vue 組件是一個 svg 路徑元素,有一個按鈕可以切換路徑。 切換是通過將路徑的d
屬性綁定到名為path
的屬性來完成的。 有一個在mount
上運行的函數,它為d
屬性生成值,我將此值設置為一個名為pathValue
的屬性。 所以,如果clicked == true
那么path = pathValue
,否則path = null
。 這按預期工作。
我進一步watch
path
,以便在發生更改時(onclick),然后應重新計算路徑長度,並將其值設置為 css 自定義變量。
<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-attribute
的值,觀察者應注意path
的變化,並調用計算屬性calculatePathLength
的設置器,更新pathLength
的watcher
應調用設置自定義屬性var(--path-length)
的吸氣劑。
所以預期的結果應該是應該記錄 pathLength,它是。 但是當它應該是非零時它是零,當它應該是零時它是非零
當您更改this.path
時,您需要給 svg 元素重新繪制的時間,然后才能計算新的getTotalLength()
。
Vue 正是為此目的提供了this.$nextTick()
函數。 要使您的代碼在上面工作:
watch: {
path: function() {
// trigger computed setter here when path is changed onclick
this.$nextTick(()=>this.calculatePathLength = this.$refs.pathID);
},
...
這個問題在這里的 vue 論壇上得到了回答,解釋是在測量路徑長度之前沒有給 svg 足夠的時間來更新,這就是vue.$nextTick()
的目的。 這是解決上述情況的代碼:
watch: {
path() {
this.$nextTick(() => this.pathLength = this.$refs.pathID.getTotalLength());
}
},
謝謝@wildhart
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.