vue :is的使用方法样例

一、前言

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

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

二、使用方法

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

<div :key="item.id" v-for="(item, index) in pane.questions">
            <div
              :is="topicName[item.type]"
            ></div>
</div>

这个意思是,外面是一个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中,大概如下:

<template>
……
</template>

<script>
……
</script>

<style lang="stylus" scoped>
@import './styl/index'

.single-topic
  width 670px
</style>

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

追逐梦想永不停

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值