es la primera vez que uso Vue (v2 no v3) y estoy atascado tratando de usar una variable (definida dentro de un método) dentro de la plantilla.
Mi código simplificado:
<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> ¿Cómo puedo obtener el valor de scaledHeight dentro de la sección de plantilla?
Si no usé this , no recibo ningún error, pero el valor de la altura siempre es 0, como si se ignorara scaledHeight .
Leí la documentación pero no me ayuda.
Fijo usando 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) }, },Encontré y resolví este problema hoy. Puede cambiar sus estilos como se muestra a continuación.
<div :class="['top-c', ...]" :style="{ height: isHovered ? 0 : scaledHeight }" >Funciona bien para mí, y espero que te ayude ~~