- 首页
- 前端开发
- 为每个 <slot> 分配一个父元素在 Vue
为每个 <slot> 分配一个父元素在 Vue
[英] Assigning a parent element for each <slot> in Vue
本文介绍了为每个 <slot> 分配一个父元素在 Vue的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 vue 组件,比如说 my-component
,它是这样的:
<div class="inner"><插槽></插槽>
当我使用组件时:
<p>这是第 1 段 </p><p>这是第 2 段 </p></my-component>
生成的 html 变成这样(通常应该如此):
<div class="inner"><p>这是第 1 段 </p><p>这是第 2 段 </p>
但相反,我正在寻找一种方法来产生这样的东西:
<div class="inner"><p>这是第 1 段 </p>
<div class="inner"><p>这是第 2 段 </p>
如何将一个 inner
div 与每个 slot
元素关联起来?
解决方案
一种方法是使用渲染函数而不是模板.这样做,您可以检查默认插槽的内容并根据需要包装内容.
这是一个例子.
console.clear()Vue.component("容器",{模板:#container-template",渲染(h){//过滤掉回车、空格等内容const content = this.$slots.default.filter(c => !c.text)//构建一个包装内容列表constwrapped = content.map(c => h('div', {attrs: {class:"inner"}}, [c]))//渲染组件return h("div", {attrs:{class:"outer"}}, 包裹)}})新的 Vue({el:#app"})
<script src="https://unpkg.com/vue@2.4.2"></script><div id="应用程序"><容器><p>这是第 1 段 </p><p>这是第 2 段 </p></容器>
I have a vue component, say my-component
, which is like this:
<div class="outer">
<div class="inner">
<slot></slot>
</div>
</div>
When I use the component:
<my-component>
<p>This is paragraph 1 </p>
<p>This is paragraph 2 </p>
</my-component>
The produced html becomes this (as it normally should):
<div class="outer">
<div class="inner">
<p>This is paragraph 1 </p>
<p>This is paragraph 2 </p>
</div>
</div>
But instead, I am looking for a way to produce something like this:
<div class="outer">
<div class="inner">
<p>This is paragraph 1 </p>
</div>
<div class="inner">
<p>This is paragraph 2 </p>
</div>
</div>
How can I associate one inner
div with each of the slot
elements?
解决方案
One way to do this would be to use a render function instead of a template. Doing that, you can examine the content of the default slot and wrap the contents as needed.
Here is an example.
console.clear()
Vue.component("container",{
template: "#container-template",
render(h){
// filter out things like carriage returns, spaces, etc
const content = this.$slots.default.filter(c => !c.text)
// build a list of wrapped content
const wrapped = content.map(c => h('div', {attrs: {class:"inner"}}, [c]))
// render the component
return h("div", {attrs:{class:"outer"}}, wrapped)
}
})
new Vue({
el: "#app"
})
<script src="https://unpkg.com/vue@2.4.2"></script>
<div id="app">
<container>
<p>This is paragraph 1 </p>
<p>This is paragraph 2 </p>
</container>
</div>
这篇关于为每个 <slot> 分配一个父元素在 Vue的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!