Vue2 如何在template模板中使用methods内处理得到的变量值
Vue2模板获取methods计算变量值的解决方案
核心问题根因
你的代码存在4处影响取值生效的问题:
- 模板中错误添加了
this前缀,Vue2模板作用域默认绑定当前组件实例,无需额外加this scaledHeight初始值为对象类型,首次渲染时会被转为无效的[object Object]字符串,浏览器无法识别为高度值- 计算得到的
scaledHeight是纯数字,CSS高度属性需要带px单位才能生效 - 仅在
mounted中触发一次高度计算,无法覆盖异步props、dom动态更新的场景
具体修正步骤
1. 修正模板style写法
移除this,补充px单位:
<div :class="['top-c']" :style="{ height: isHovered ? '0px' : `${scaledHeight}px` }" > </div>
2. 修正data初始值
将scaledHeight初始值改为数字类型的0:
data: function () { return { isHovered: false, scaledHeight: 0, // 修正为数字类型初始值 } }
3. 新增动态更新逻辑
如果props的datum是异步传入、或者会动态变化,需要新增watch监听,确保dom渲染完成后再计算高度:
export default { // 省略其他配置 watch: { datum: { immediate: true, handler() { this.$nextTick(() => { // 确保ref对应的dom已经渲染完成 if (this.$refs.topCContainerRef) { this.matchHeight() } }) } } }, methods: { matchHeight() { const topCContainerHeight = this.$refs.topCContainerRef.clientHeight // 确保容器高度不为0再计算 if (!topCContainerHeight) return const heightScale = scaleLinear([0, 100], [20, topCContainerHeight]) this.scaledHeight = heightScale(this.datum) }, } }
4. 额外注意事项
需要给top-c-container元素设置明确的可计算高度(比如固定高度、父级高度继承),否则clientHeight取值为0,计算出来的scaledHeight也会一直为20(d3 scale输入0时的输出值)。如果容器高度会随窗口resize变化,还需要新增resize事件监听触发matchHeight重新计算。
内容的提问来源于stack exchange,提问作者marielle
相关产品推荐
相关产品推荐

