iT邦幫忙

0

Vue2.X render 參數使用

vue
  • 分享至 

  • xImage

您好:
參考
https://codertw.com/%E5%89%8D%E7%AB%AF%E9%96%8B%E7%99%BC/241875/
其中
createElement( 標籤名, 標籤屬性, 標籤裡的內容)

我於以下程式碼中,設定如下

關於"標籤屬性",我該如何設定?
我設過
'h' + this.level, //1. tag name 標籤名稱
{title: 'ZZ' },
this.$slots.default //3. 子元件中的陣列
但 沒有效果

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
</head>

<body>
    <h1 title="helloXX">Hello</h1>
    <div id="app">
        <child v-bind:level="2">Hello world!</child>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

    <script>
        Vue.component('child', {
            render: function(createElement) {
                return createElement(
                    'h' + this.level, //1. tag name 標籤名稱                     
                    this.$slots.default //3. 子元件中的陣列
                )
            },
            props: {
                level: {
                    type: Number,
                    required: true
                }
            }
        })
        new Vue({
            el: "#app"
        })
    </script>

</body>

</html>
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
Ares
iT邦研究生 3 級 ‧ 2021-04-11 12:23:02
最佳解答

VNode 內的 data 會渲染為標籤屬性

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>JS Bin</title>
</head>

<body>
    <h1 title="helloXX">Hello</h1>
    <div id="app">
        <child v-bind:level="2">Hello world!</child>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.0.3/vue.js"></script>

    <script>
        Vue.component('child', {
            render: function(createElement) {
                this.$slots.default[0].tag = 'div' // 標籤
                this.$slots.default[0].data = { class: 'foo' } // 屬性
                return createElement(
                    'h' + this.level,
                    this.$slots.default
                )
            },
            props: {
                level: {
                    type: Number,
                    required: true
                }
            }
        })
        new Vue({
            el: "#app"
        })
    </script>

</body>

</html>
noway iT邦研究生 3 級 ‧ 2021-04-11 12:36:41 檢舉

您好: 謝謝。
所以不是在 return createElement(
'h' + this.level,
this.$slots.default
) 設定?
為何說
createElement( 標籤名, 標籤屬性, 標籤裡的內容)
另外,我單純測試
this.$slots.default[0].data = {
class: 'foo',
title: 'ZZZZ'
} // 屬性

但title 並沒有作用
謝謝!

Ares iT邦研究生 3 級 ‧ 2021-04-11 12:52:36 檢舉

你這邊的話
標籤名: h2
標籤屬性: h2的屬性
標籤內容: h2裡面的內容
如果要設定 title 可以這樣:
this.$slots.default[0].data = { attrs: { title: 'title' } }

noway iT邦研究生 3 級 ‧ 2021-04-24 09:55:14 檢舉

謝謝您

我要發表回答

立即登入回答