问题
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