我想要实现崩溃并隐藏在vuejs中。
但我认为,如果它在vue3中不起作用
我得到了这个错误,Header.vue?76f0:68 Uncaught (承诺) TypeError:无法读取未定义的属性(读'myText')
这是我的密码
<button class="border-0 navbar" @click="toggle()">
<Links
class="color-dark"
ref="myText"
:style="[isActive ? { height: computedHeight } : {}]"
/>
function toggle() {
this.isActive = !this.isActive
}
function initHeight() {
this.$refs.myText.style.height = 'auto'
this.$refs.myText.style.position = 'absolute'
this.$refs.myText.style.visibility = 'hidden'
this.$refs.myText.style.display = 'block'
const height = getComputedStyle(this.$refs['myText']).height
this.computedHeight = height
this.$refs.myText.style.position = null
this.$refs.myText.style.visibility = null
this.$refs.myText.style.display = null
this.$refs.myText.style.height = 0
}
watchEffect(async () => {
initHeight()
})我正在将这段代码复制到vuejs3 (这很有效,但我需要vuejs3)
发布于 2022-04-07 22:22:50
看上去它比代码中的东西更重要。从示例中进行的简单vue2=>vue3转换工作得很好
示例:
Vue.createApp({
data() {
return {
isActive: false,
computedHeight: 0
}
},
methods: {
toggle: function() {
this.isActive = !this.isActive;
},
initHeight: function() {
this.$refs['myText'].style.height = 'auto';
this.$refs['myText'].style.position = 'absolute';
this.$refs['myText'].style.visibility = 'hidden';
this.$refs['myText'].style.display = 'block';
const height = getComputedStyle(this.$refs['myText']).height;
this.computedHeight = height;
this.$refs['myText'].style.position = null;
this.$refs['myText'].style.visibility = null;
this.$refs['myText'].style.display = null;
this.$refs['myText'].style.height = 0;
}
},
mounted: function() {
this.initHeight()
}
}).mount("#app");p {
height: 0;
overflow: hidden;
transition: 1s;
}<script src="https://unpkg.com/vue@3.2.31/dist/vue.global.prod.js"></script>
<div id="app">
<p ref="myText" :style="[isActive ? { height : computedHeight } : {}]">
Now it's smooth - getting closer to BS4 collapse, but now I need to know the exact height of each section at a particular screen size to set the max-height. Over-compensating max-width work ok, but is still a bit 'jerky'. Is there a way to calculate an
elements height before starting the show/hide? If the max-height value is too small, elements overlap.
</p>
<button @click="toggle">Open / Close</button>
</div>
但是,我看到您使用的是watchEffect,因此我推测您可能正在使用(某些♂️)组合API功能。在这种情况下,手表将在挂载前执行,因此它将运行initHeight,这将失败。
如果您使用的是复合api,那么可能会有更多的东西导致它不能工作,所以您可能需要显示更多的代码。或者,您可以坚持类API,它的工作方式与在vue2中一样。
https://stackoverflow.com/questions/71789286
复制相似问题