Vue.js - 以编程方式设置插槽内容 [英] Vue.js - set slot content programmatically

查看:35
本文介绍了Vue.js - 以编程方式设置插槽内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法可以从组件内部设置/覆盖插槽的内容?喜欢

模板:

<插槽></插槽>

JS:

出口默认{...安装(){this.$slot.render("");}...}

我知道我可以在我的元素上使用 v-html 来动态地将内容推送到组件模板中,但我的意思不仅仅是纯 HTML,我指的是带有 Vue 指令的 HTML.喜欢:

JS:

出口默认{...安装(){this.$slot.default.render('<button @click="submit">OK</button>');},方法: {提交() {//这里我想得到:)}}...}

基本上,我希望 Vue 在我的组件范围内呈现(像解析和呈现,而不是像 innerHTML)特定的字符串,并放置在我的组件中的特定位置.原因是我通过 AJAX 从服务器获取新内容.

很抱歉,我在谷歌搜索了 2 天后仍然无法理解.

非常感谢!

解决方案

根据 this 您可以通过编程方式实例化组件并插入插槽内容.

从'Button.vue'导入按钮从'vue'导入Vuevar ComponentClass = Vue.extend(Button)var instance = new ComponentClass({道具数据:{ 类型:'主要'}})instance.$slots.default = [ '点击我!']instance.$mount()//不传递任何内容this.$refs.container.appendChild(instance.$el)

is there any way how can I set/override slot's content from inside the component? Like

Template:

<div>
    <slot></slot>
</div>

JS:

export default {
    ...
     mounted() {
        this.$slot.render("<button>OK</button>");
     }
    ...
}

I know I can use v-html on my element to dynamically push content into component template, but I mean not just pure HTML I mean HTML with Vue directives. Like:

JS:

export default {
    ...
     mounted() {
        this.$slot.default.render('<button @click="submit">OK</button>');
     },
    methods: {
        submit() {
            // Here I want to get :)
        }
    }
    ...
}

Basically I want Vue to render (like parse and render, not like innerHTML) certain string in scope of my component and put in on certain spot in my component. The reason is I get the new content from server via AJAX.

I'm sorry but I can't still get my head around after 2 days of googling.

Thanks a lot!

解决方案

According to this you can instantiate a component programmatically and insert slot content as well.

import Button from 'Button.vue'
import Vue from 'vue'
var ComponentClass = Vue.extend(Button)
var instance = new ComponentClass({
    propsData: { type: 'primary' }
})
instance.$slots.default = [ 'Click me!' ]
instance.$mount() // pass nothing
this.$refs.container.appendChild(instance.$el)

这篇关于Vue.js - 以编程方式设置插槽内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆