這是我第一次使用 Vue(v2 不是 v3),我一直在嘗試在模板中使用變數(在方法中定義)。
我的簡化代碼:
<template>
<div class="container" @mouseover="isHovered = true" @mouseleave="isHovered = false">
<div class="c-container">
<div ref="topCContainerRef" class="top-c-container">
<div
:class="['top-c', ...]"
:style="{ height: `${isHovered ? 0 : this.scaledHeight}` }" // <-- HERE I need `scaledHeight`
>
</div>
</div>
</div>
</div>
</template>
<script>
import { scaleLinear } from 'd3-scale'
export default {
name: 'MyComponent',
components: { },
props: {
...,
datum: {
type: Number,
required: true,
},
...
},
data: function () {
return {
isHovered: false,
scaledHeight: {},
}
},
mounted() {
this.matchHeight()
},
methods: {
matchHeight() {
const topCContainerHeight = this.$refs.topCContainerRef.clientHeight
const heightScale = scaleLinear([0, 100], [20, topCContainerHeight])
const scaledHeight = heightScale(this.datum)
this.scaledHeight = scaledHeight // I want to use this value inside the template
},
},
}
</script>
如何獲取scaledHeight模板部分內的值?
如果我沒有使用this,我不會得到任何錯誤,但高度值始終為 0,就像scaledHeight被忽略..
我閱讀了檔案,但它對我沒有幫助
uj5u.com熱心網友回復:
我今天遇到并解決了這個問題。您可以像下面這樣更改樣式。
<div
:class="['top-c', ...]"
:style="{ height: isHovered ? 0 : scaledHeight }"
>
對我來說很好用,希望對你有幫助~~
uj5u.com熱心網友回復:
固定使用 computed
computed: {
computedHeight: function () {
return this.isHovered ? 0 : this.matchHeight()
},
},
methods: {
matchHeight() {
const topCContainerHeight = this.$refs.topCContainerRef.clientHeight
const heightScale = scaleLinear([0, 100], [20, topCContainerHeight])
return heightScale(this.datum)
},
},
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/353953.html
