Home > Software design >  Use a variable defined in a method inside the template
Use a variable defined in a method inside the template

Time:11-09

it's the first time I use Vue (v2 not v3) and I'm stucked trying to use a variable (defined inside a methods) inside the template.

My semplified 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 can I get the value of scaledHeight inside the template section?

If I didn't use this, I get no error but the height value is always 0, like scaledHeight is ignored..

I read the documentation but it doesn't help me

CodePudding user response:

I encountered and solved this problem today. You can change your styles like below.

<div
    :class="['top-c', ...]"
    :style="{ height: isHovered ? 0 : scaledHeight }" 
>

It works fine for me, and hope it will help you~~

CodePudding user response:

Fixed using 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)
    },
  },
  • Related