Home  >  Q&A  >  body text

Using variables defined in methods in templates

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

P粉681400307P粉681400307108 days ago377

reply all(2)I'll reply

  • P粉729198207

    P粉7291982072024-04-07 13:42:34

    I encountered and solved this problem today. You can change the style like below.

    It works very well for me, I hope it helps you~~

    reply
    0
  • P粉186017651

    P粉1860176512024-04-07 11:59:15

    Use compulated Repair

    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)
        },
      },

    reply
    0
  • Cancelreply