在Vue Router中有条件地导入组件

时间:2018-07-16 13:35:44

标签: vue.js vue-component vue-router

我遇到了这个问题,我想在同一条路线上导入不同的组件。

这很好

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:id="@+id/text"
        android:gravity="center"
        android:textSize="20sp"
        android:textColor="#000000"/>

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:id="@+id/imageView"
        android:background="@color/colorAccent"
        android:scaleType="centerCrop"/>

</LinearLayout>

这不起作用

import Mycomponent from '@/views/Mycomponent'

{
  name: 'My component name',
  path: somepath,
  component: Mycomponent,
}

这也不起作用

import Mycomponent from '@/views/Mycomponent'
import MycomponentDifferent from '@/views/MycomponentDifferent'

{
  name: 'My component name',
  path: somepath,
  component: () => {
    if(true) {
     console.log(Mycomponent) // You can see in console whole component
     return Mycomponent
    } else {
     return MycomponentDifferent
    }
  }
}

1 个答案:

答案 0 :(得分:0)

您是否可以在component中使用函数?
可以使用getter代替函数:

import Mycomponent from '@/views/Mycomponent'
import MycomponentDifferent from '@/views/MycomponentDifferent'

{
  name: 'My component name',
  path: somepath,
  get component() {
    if(true) {
     console.log(Mycomponent) // You can see in console whole component
     return Mycomponent
    } else {
     return MycomponentDifferent
    }
  }
}