本文介绍了有条件地渲染父元素,保留内部 html的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有任何内置方法可以有条件地显示父元素?
举例说明:
<span>不管怎样总是渲染这个</span></a
解决方案
我认为这是自定义指令的工作.我将此作为快速 POC 制作:
Vue.directive('showButKeepInner', {绑定(EL,绑定){bindings.def.wrap = function(el) {//找到所有下一个有数据移动的兄弟并移回 el而 (el.nextElementSibling && el.nextElementSibling.dataset.moved) {el.appendChild(el.nextElementSibling).removeAttribute('数据移动')}el.hidden = 假}bindings.def.unwrap = function(el) {//将 el 的所有孩子移到外面并用数据移动的属性标记它们Array.from(el.children).forEach(child => {el.insertAdjacentElement('afterend', child).setAttribute('data-moved', true)})el.hidden = 真}},插入(埃尔,绑定){bindings.def[bindings.value ?'wrap' : 'unwrap'](el)},更新(EL,绑定){bindings.def[bindings.value ?'wrap' : 'unwrap'](el)}})新的 Vue({el: '#app',数据: {someCondition: 假}})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script><div id="应用程序"><p><button v-on:click="someCondition = !someCondition">{{ someCondition }}</button></p><a v-show-but-keep-inner="someCondition" href="/"><span>不管怎样总是渲染这个</span></a>
Is there any built-in way to go about conditionally showing a parent element?
To illustrate:
<a v-show-but-keep-inner="someCondition">
<span>This is always rendered no matter what</span>
</a
解决方案
I think it's a job for custom directive. I made this one as a quick POC:
Vue.directive('showButKeepInner', {
bind(el, bindings) {
bindings.def.wrap = function(el) {
// Find all next siblings with data-moved and move back into el
while (el.nextElementSibling && el.nextElementSibling.dataset.moved) {
el.appendChild(el.nextElementSibling).removeAttribute('data-moved')
}
el.hidden = false
}
bindings.def.unwrap = function(el) {
// Move all children of el outside and mark them with data-moved attr
Array.from(el.children).forEach(child => {
el.insertAdjacentElement('afterend', child).setAttribute('data-moved', true)
})
el.hidden = true
}
},
inserted(el, bindings) {
bindings.def[bindings.value ? 'wrap' : 'unwrap'](el)
},
update(el, bindings) {
bindings.def[bindings.value ? 'wrap' : 'unwrap'](el)
}
})
new Vue({
el: '#app',
data: {
someCondition: false
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.10/vue.min.js"></script>
<div id="app">
<p>
<button v-on:click="someCondition = !someCondition">{{ someCondition }}</button>
</p>
<a v-show-but-keep-inner="someCondition" href="/">
<span>This is always rendered no matter what</span>
</a>
</div>
这篇关于有条件地渲染父元素,保留内部 html的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!