在模板中使用在方法中定义的变量
P粉681400307
P粉681400307 2024-04-06 18:10:25
0
2
505

这是我第一次使用 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粉681400307
P粉681400307

全部回复(2)
P粉729198207

我今天遇到并解决了这个问题。 您可以像下面这样更改样式。

对我来说效果很好,希望对你有帮助~~

P粉186017651

使用 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)
    },
  },
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!