Using variables defined in methods in templates
P粉681400307
P粉681400307 2024-04-06 18:10:25
0
2
677

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粉681400307
P粉681400307

reply all(2)
P粉729198207

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~~

P粉186017651

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)
    },
  },
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template