This is my first time using Vue (v2 not v3) and I've been trying to use variables inside templates (defined inside methods).
My simplified code:
<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>
How to get the value of scaledHeight in the template part?
If I don't use this, I don't get the error, but the height value is always 0, as if scaledHeight is ignored.
I read the documentation but it didn't help me
I encountered and solved this problem today. You can change the style like below.
Use
compulatedRepaircomputed: { 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) }, },