这是我第一次使用 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 被忽略一样。
我阅读了文档,但它对我没有帮助
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我今天遇到并解决了这个问题。 您可以像下面这样更改样式。
使用
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) }, },