1. 程式人生 > >獲取表格行數和高度為0的原因及解決方法-vue填坑

獲取表格行數和高度為0的原因及解決方法-vue填坑

vue真的坑太多!雖然入門簡單易上手,但是,大專案真的不建議使用此框架,分分鐘重新整理世界觀,很多生命週期問題、載入問題、傳值問題、監聽問題……
能填一個是一個,能救一人是一人,特意寫篇標題明顯的,希望能一下就被檢索到。

表格存在且有內容,行數可被打印出來,但是獲取到的行數和高度卻為0。
程式碼:

methods: {
   aaa () {
        console.log('——————————————————測試——————————————————');
        console.log('表格html:', this.$refs.abc);
        console.
log('表格.rows:', this.$refs.abc.rows); console.log('表格.rows.length:', this.$refs.abc.rows.length); console.log('表格.offsetHeight:', this.$refs.abc.offsetHeight); console.log('——————————————————測試——————————————————'); } }

執行結果:
在這裡插入圖片描述

為何如此?

因為是渲染之前列印的這個陣列,看到的卻是渲染後的資料,通俗的講,就是這個dom結構還沒載入完,js就執行了。

如何解決?

等dom結構載入完成後再去獲取這個陣列。
vue等待渲染完執行的函式: vm.$nextTick(function({console.log(…)}))

修改後程式碼:

methods: {
   aaa () {
        this.$nextTick(() => {
             console.log('——————————————————測試——————————————————');
             console.log('表格html:', this.$refs.abc);
             console.log
('表格.rows:', this.$refs.abc.rows); console.log('表格.rows.length:', this.$refs.abc.rows.length); console.log('表格.offsetHeight:', this.$refs.abc.offsetHeight); console.log('——————————————————測試——————————————————'); }) } }

修改後執行結果:
在這裡插入圖片描述