簡體   English   中英

如何以編程方式創建 Vue.js 插槽?

[英]How to create Vue.js slot programmatically?

我有以下帶插槽的組件:

<template>
    <div>
        <h2>{{ someProp }}</h2>
        <slot></slot>
    </div>
</template>

由於某些原因,我必須手動實例化這個組件。 這就是我的做法:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
}).$mount(body);

問題是:我無法以編程方式創建插槽內容。 到目前為止,我可以創建簡單的基於字符串的插槽:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
});

// Creating simple slot
instance.$slots.default = ['Hello'];

instance.$mount(body);

問題是 - 如何$slots編程方式創建$slots並將其傳遞給我使用new創建的實例?

注意:我沒有使用完整版本的 Vue.js(僅限運行時)。 所以我沒有可用於即時編譯模板的 Vue.js 編譯器。

我查看了Vue.js TypeScript 定義文件,我在 Vue 組件實例上發現了一個未記錄的函數: $createElement() 我的猜測是,它與傳遞給組件的render(createElement)函數的函數相同。 因此,我可以將其解決為:

const Constr = Vue.extend(MyComponent);
const instance = new Constr({
    propsData: { someProp: 'My Heading' }
});

// Creating simple slot
const node = instance.$createElement('div', ['Hello']);
instance.$slots.default = [node];

instance.$mount(body);

但這顯然是沒有記錄的,因此是有問題的方法。 如果有更好的方法可用,我不會將其標記為已回答。

我想我終於偶然發現了一種以編程方式創建插槽元素的方法。 據我所知,該方法似乎不適用於功能組件。 我不知道為什么。

如果您正在為組件實現自己的渲染方法,則可以使用 createElement 方法(或您在渲染方法中為其指定別名的任何方法)以編程方式創建傳遞給子元素的槽,並傳遞包含 { slot : NAME_OF_YOUR_SLOT } 后跟該插槽中的子項數組。

例如:

 Vue.config.productionTip = false Vue.config.devtools = false; Vue.component('parent', { render (createElement) { return createElement('child', [ createElement('h1', { slot: 'parent-slot' }, 'Parent-provided Named Slot'), createElement('h2', { slot: 'default' }, 'Parent-provided Default Slot') ]) } }) Vue.component('child', { template: '<div><slot name="parent-slot" /><slot /></div>' }) new Vue({ el: '#app', template: '<parent />' })
 <script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.js"></script> <div id='app'> </div>

(這並沒有真正回答How to create Vue.js slot programatically? 。但它確實解決了您的問題。)

與使用$createElement()相比,這個技巧不那么駭人聽聞。

基本上,創建一個將MyComponent注冊為本地組件的新組件。

const Constr = Vue.extend({
  template: `
  <MyComponent someProp="My Heading">
    <div>slot here !!!</div>
  </MyComponent>
  `,
  components: {
    MyComponent: MyComponent
  }
});
const instance = new Constr().$mount('#app');

演示: https : //jsfiddle.net/jacobgoh101/shrn26p1/

我剛剛在 vue 論壇上找到了一個答案: slots

原理是:沒有像 createElement('slot'..) 這樣的東西,而是有一個渲染函數,它提供帶槽的innerHtml 作為函數:$scopedSlots.default()

用法:

 render: function (createElement) { const self = this; return createElement("div", this.$scopedSlots.default()); }

如果您想在沒有為插槽提供內容的情況下提供默認值,您需要自己編寫一個區分並呈現其他內容。 (上面的鏈接有一個更詳細的例子)

該函數返回一個數組,因此它不能用作渲染函數的根。 它需要被包裝到單個容器節點中,如上例中的div

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM