问题
In React I can do something like this:
// parent component
export default (){
return (
<div>
<div>1</div>
<ChildComponent />
<div>5</div>
</div>
);
}
// child component
export default (){
return (
<React.Fragment>
<div>2</div>
<div>3</div>
<div>4</div>
</React.Fragment>
);
};
// compiled html tags in browser .
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
But in Vue , when I've done the same thing , something went difference .
// parent component
<template>
<div>
<div>1</div>
<child-component />
<div>5</div>
</div>
</template>
<script>
import childComponent from 'path/to/childComponent';
export default {
components: { childComponent }
}
</script>
-------------------------------------------------------------
// child component
<template>
<div id='have_to_write_in_vue'>
<div>2</div>
<div>3</div>
<div>4</div>
<div>
</template>
// compiled html tags in browser .
<div>1</div>
<div id='have_to_write_in_vue'>
<div>2</div>
<div>3</div>
<div>4</div>
</div>
<div>5</div>
The difference is that 'DIV' tags are not at same level in Vue . How can I handle this ?
I'm asking this is because of something went wrong when useless nesting appearing.
回答1:
I recently used this package. https://www.npmjs.com/package/vue-fragment.
Its a fragment component for Vue.js. Basically provides root-less components.
回答2:
The lack of a first party Fragment component in Vue drives me nuts!
I had looked at the the vue-fragment
npm package, but it made me nervous at how much they were doing and felt there had to be a better way.
I came up with something extremely lightweight... It works because functional components are allowed to return multiple root nodes.
This doesn't work 100% like Reacts, however. In React, you can actually use a React.Fragment
as the root node in your app, for example. This seems to only work in Vue when you're already within a component (ie: it can't be the root node of your base component).
const Fragment = {
functional: true,
render: (h, ctx) => ctx.children
}
to use it...
<Fragment>
<div>Div 1</div>
<div>Div 2</div>
</Fragment>
Super useful...
{someCondition && (
<Fragment>
<div>yay i can use multiple nodes</div>
<div>:)</div>
</Fragment>
)}
<div>
Some inline text {condition ? (
<Fragment>now I can use <strong>html</strong> and {variables}</Fragment>
) : (
<Fragment>So many possibilities</Fragment>
)}
</div>
回答3:
Apparently, Vue.js v3 now supports fragments out of the box: Fragments (Vue.js documetnation)
来源:https://stackoverflow.com/questions/59388851/is-there-something-like-react-fragment-in-vue