首頁  >  問答  >  主體

在模板中使用方法中定義的變數

這是我第一次使用 Vue(v2 而不是 v3),我一直在嘗試在模板內使用變數(在方法內定義)。

我的簡化程式碼:

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

如何取得範本部分中 scaledHeight 的值?

如果我沒有使用 this,我不會收到錯誤,但高度值始終為 0,就像 scaledHeight 被忽略一樣。

我閱讀了文檔,但它對我沒有幫助

P粉681400307P粉681400307194 天前601

全部回覆(2)我來回復

  • P粉729198207

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

    我今天遇到並解決了這個問題。 您可以像下面這樣更改樣式。

    對我來說效果很好,希望對你有幫助~~

    回覆
    0
  • P粉186017651

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

    使用 compulated 修復

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

    回覆
    0
  • 取消回覆