How to show a different html element/tag based on supplied prop in VueJs

我与影子孤独终老i 提交于 2021-01-29 15:18:39

问题


In Vuejs a <template> can only contain one root element, but what to do if you want to render different html element based on a prop?

For example, I have a <heading> component which I want to show/render <h1> if title prop, prop: {title: {type: String, required: true}} is title, and show/render <h3> if it is subtitle

And that reminds me, what if I want to do this for all h tags ? I mean based on prop condition, show one of these <h1> to <h6> ?


回答1:


The is attribute will allow you to dynamically render whatever html element (or custom component - needs to be imported and registered though) you need. You can use it for example like this:

<template>
  <template :is="headingType">
    {{ headingContent }}
  </template>
</template>

<script>
  export default {
    props: {
      headingType: {
        type: String,
        default: 'h2' // you can pass anything from 'h1' to 'h6' here   
      },
      headingContent: {
        type: String,
        required: true
      }
    }
  }
</script>

More Info: https://vuejs.org/v2/api/#is



来源:https://stackoverflow.com/questions/58892537/how-to-show-a-different-html-element-tag-based-on-supplied-prop-in-vuejs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!