mounted中使用this.$refs报unfidned

2020-04-08 11:17:36 查看 1874 回复 0
 <cube-slide-item v-for="(tab, index) in tabs" :key="index">
                <component :is="tab.component" :data="tab.data" ref="component"></component>
</cube-slide-item>

使用了v-for遍历,生成动态组件

aaa

挂载完毕初始化默认选中值。

尴尬的事情出现了。。。

cccc

动态组件引用失败~

但是这段代码在其他项目是正常的。

看了看代码,发现这个使用一些“优化”写法。

例如组件懒加载

export default {
  name: 'Home',
  computed: {
    tabs() {
      return [
        {
          label: '推荐',
          component: () => import('components/recommend/recommend'),
          data: { }
        },
        {
          label: '歌手',
          component: () => import('components/singer/singer'),
          data: { }
        },
        {
          label: '排行',
          component: () => import('components/rand/rand'),
          data: { }
        },
        {
          label: '搜索',
          component: () => import('components/search/search'),
          data: { }
        }
      ]
    }
  },

严重怀疑是不是它的锅。。。

代码换成标准引用方式

import Recommend from 'components/recommend/recommend'
import Rand from 'components/rand/rand'
import Singer from 'components/singer/singer'
import Search from 'components/search/search'

export default {
  name: 'Home',
  computed: {
    tabs() {
      return [
        {
          label: '推荐',
          // component: () => import('components/recommend/recommend'),
          component: Recommend,
          data: { }
        },
        {
          label: '歌手',
          // component: () => import('components/singer/singer'),
          component: Singer,
          data: { }
        },
        {
          label: '排行',
          // component: () => import('components/rand/rand'),
          component: Rand,
          data: { }
        },
        {
          label: '搜索',
          // component: () => import('components/search/search'),
          component: Search,
          data: { }
        }
      ]
    }
  },

代码顺利运行~~

估计是懒加载加载时机导致的。mounted的时候其实并不存在,读取的时候自然读不到。