vue :is的使用方法样例

一、前言

最近发现vue项目中用到了:is来动态切换不同组件,在此记录下本人项目中的使用方法。

(PS:本人项目中用的比较复杂,就这样记录了)

二、使用方法

1.首先,有一个页面中写了:

这个意思是,外面是一个v-for循环,pane.questions是一个数组,其中的type字段是0-4的值,对应会切换为 :is="topicName[0]" :is="topicName[1]"等组件。

2.topicName字段,是这样的:

import {
  TOPICNAME,
} from '@/components/topic/config'

……

  data() {
    return {
      topicName: TOPICNAME,
    }
  },

然后,项目名\src\components\topic\config\index.js文件里,是这样写的:

export const TOPICNAME = [
  'single-topic',
  'multiple-topic',
  'judgement-topic',
  'fill-topic',
  'q-a-topic',
]

所以,如果是 :is="topicName[0]",就相当于 :is="single-topic"
如果是 :is="topicName[1]",就相当于 :is="multiple-topic"
以此类推。

3.然后,在页面中,还有:

import SingleTopic from '@/components/topic/single-topic'
import MultipleTopic from '@/components/topic/multiple-topic'
import JudgementTopic from '@/components/topic/judgement-topic'
import FillTopic from '@/components/topic/fill-topic'
import QATopic from '@/components/topic/q-a-topic'

……

export default {
  components: {
    SingleTopic,
    MultipleTopic,
    JudgementTopic,
    FillTopic,
    QATopic,
  },

其中,先import,然后在components里声明,就可以在:is里使用了;
需要注意, :is="single-topic"时,就会自动关联到组件SingleTopic(把首字母变大写并且去掉了下划线);
其它4个也类似。

4.最后,在页面:项目名\src\components\topic\single-topic.vue中,大概如下:






这个就是当 :is="single-topic"时,就会自动关联到components里的组件SingleTopic,由于有import SingleTopic from '@/components/topic/single-topic',就会加载这个页面的内容了。

你可能感兴趣的:(vue.js,前端,javascript)