我有一个简化的 Vue 组件,如下所示。
这是模板
<template>
<slot></slot>
</template>
该插槽可能包含 HTML,这就是为什么我决定使用插槽而不是简单绑定到的 prop。我想保持这种状态。
我有一个从服务器获取新 HTML 的方法。我想使用这个新的 HTML 来更新插槽。我不确定插槽是否是反应性的以及如何实现这一点。
我可以使用查看默认插槽this.$slots.default[0]
,但我不知道如何用 HTML 内容字符串更新它。简单地将字符串分配给元素显然是不正确的,.innerHtml
不起作用,因为它不是可用的功能,并且.text
不起作用。我假设即使槽对象上存在文本元素,元素属性也优先。
根据评论中的建议,我已经尝试过将此与计算机属性一起使用。
<span v-html="messageContent"><slot></slot></span>
但现在的问题是它覆盖了传递给我的插槽。
如何在 Vue.JS 中使用新的 HTML 响应式更新插槽?
我认为你的问题源于对如何的误解<slot>
本质上是在 VueJS 中工作的。槽用于将使用父组件的内容交织到子组件中。将其视为 HTML 等价物v-bind:prop
。当你使用v-bind:prop
在组件上,您可以有效地将数据传递到子组件中。这与插槽相同。
如果您没有任何具体的示例或代码,这个答案是at best只是猜测。我假设你的父组件本身就是一个 VueJS 应用程序,而子组件是保存<slot>
元素。
<!-- Parent template -->
<div id="app">
<custom-component>
<!-- content here -->
</custom-component>
</div>
<!-- Custom component template -->
<template>
<slot></slot>
</template>
在这种情况下,应用程序有一个默认的基态,它将静态 HTML 传递给子组件:
<!-- Parent template -->
<div id="app">
<custom-component>
<!-- Markup to be interweaved into custom component -->
<p>Lorem ipsum dolor sit amet.</p>
</custom-component>
</div>
<!-- Custom component template -->
<template>
<slot></slot>
</template>
然后,当事件被触发时,您希望用新的传入标记替换该基态标记。这可以通过将传入的 HTML 存储在data
属性,并简单地使用v-html
有条件地渲染它。假设我们想将传入的标记存储在应用程序的vm.$data.customHTML
:
data: {
customHTML: null
}
然后你的模板将如下所示:
<!-- Parent template -->
<div id="app">
<custom-component>
<div v-if="customHTML" v-html="customHTML"></div>
<div v-else>
<p>Lorem ipsum dolor sit amet.</p>
</div>
</custom-component>
</div>
<!-- Custom component template -->
<template>
<slot></slot>
</template>
请注意,与您尝试过的代码相比,差异在于:
- 它是父组件(即消耗组件) 负责规定要传递给子级的标记类型
- 子组件如下dumb正如它得到的那样:它只是接收标记并将其呈现在
<slot>
element
请参阅下面的概念验证:
var customComponent = Vue.component('custom-component', {
template: '#custom-component-template'
});
new Vue({
el: '#app',
data: {
customHTML: null
},
components: {
customComponent: customComponent
},
methods: {
updateSlot: function() {
this.customHTML = '<p>Foo bar baz</p>';
}
}
});
.custom-component {
background-color: yellow;
border: 1px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.min.js"></script>
<div id="app">
<h1>I am the app</h1>
<button type="button" @click="updateSlot">Click me to update slot content</button>
<custom-component>
<div v-if="customHTML" v-html="customHTML">
</div>
<div v-else>
<p>Lorem ipsum dolor sit amet.</p>
</div>
</custom-component>
</div>
<!-- custom-component template -->
<script type="text/template" id="custom-component-template">
<div class="custom-component">
<h2>I am a custom component</h2>
<!-- slot receives markup set in <custom-component> -->
<slot></slot>
</div>
</script>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)