For example, there is such a demand, sub-assemblies passed over by the parent component
props
, to dynamically display<h1>
the<h6>
label, may be the first matterreact
, think aboutvue
how to achieve it?
Vue implementation
Parent component
<template>
<div>
<Son :tagSize="1"/>
</div>
</template>
<script>
import Son from '../components/Son';
export default {
name: "Father",
components:{
Son
}
};
</script>
Subassembly
<template>
<div>
<h1 v-if="tagSize === 1">测试</h1>
<h2 v-else-if="tagSize === 2">测试</h2>
<h3 v-else-if="tagSize === 3">测试</h3>
<h4 v-else-if="tagSize === 4">测试</h4>
<h5 v-else-if="tagSize === 5">测试</h5>
<h6 v-else>测试</h6>
</div>
</template>
<script>
export default {
name: "Son",
props: {
tagSize: {
type:Number,
default:1
}
}
};
</script>
With vue
template syntax that we can also achieve the above requirements, but can not because the dynamic html
label it is not very flexible, lower imagine, if you can modify the label, the label directly by way of stitching, for example "<h"+tagSize+">测试</h"+tagSize+">"
the way, in such a way to deal with this demand, then obviously very convenient, ado, take a look at react
implementation.
React implementation
Parent component
import React from 'react';
import Child from './Child.js';
class Father extends React.Component{
render(){
return (
<React.Fragment>
<Child size = { 1 }/>
</React.Fragment>
)
}
}
export default Father;
Subassembly
import React from 'react';
const Child = (props)=>{
let MarkUp = `h${props.size}`;
return (
<React.Fragment>
<MarkUp>你好</MarkUp>
</React.Fragment>
)
}
export default Child;
Compared'll find two ways react
to achieve this kind of demand would be more appropriate, react
syntax of JSX
grammar, syntax personal feeling than vue
the template
template syntax is more flexible, but Vue
now also has support JSX
.