在Vue中使用插槽

如下方法傳值存在兩個問題:
1.不能去掉外面包裹的標籤
2.若是要傳值的太多,這種方法很搓很難閱讀javascript

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="./vue.js"></script>
    <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
    <child content="<p>My name is Tom Cat</p>"></child>
</div>
<script type="text/javascript">
    Vue.component("child", {
        props: ["content"],
        template: `<div>
                        <p>hello</p>
                        <br/>//把html標籤轉義顯示出來了:<br/><br/>
                        {{content}}<br/>
                        <br/>//正常渲染了html標籤(也顯示了外面包裹的div):
                        <div v-html='this.content'></div>
                        //而模版佔位符template也不能去掉外面包裹的標籤,並且整個都不渲染了:<br/>
                        <template v-html='this.content'></template>
                        <br/>
                    </div>`
    });
    var vm = new Vue({
        el: "#root"
    })
</script>
</body>
</html>

那用啥方法?用插槽啊!
插槽的使用細節:html

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script src="./vue.js"></script>
    <!-- <script src="http://cdn.staticfile.org/vue/2.6.10/vue.common.dev.js"></script> -->
</head>
<body>
<div id="root">
    <child>
        //這是插槽咯:
        <h1>world</h1>
    </child>

    //注意:content是保留關鍵字,不能用做組件,so 用my-content(用myContent這樣的駝峯命名會報錯):
    <my-content1>
        <div class="header">header</div>
        <div class="footer">footer</div>
    </my-content1>

    <br>//具名插槽:
    <my-content2>
        <div class="header" slot="header">header</div>
        <div class="footer" slot="footer">footer</div>
    </my-content2>
</div>
<script type="text/javascript">
    Vue.component("child", {
        //props: ["content"],
        template: `<div>
                        <p>hello</p>
                        <slot>默認內容,當父組件不傳遞插槽內容的時候顯示</slot>
                    </div>`
    });

    Vue.component("my-content1", {
        //props: ["content"],
        template: `<div>
                        <slot></slot>
                        <div class='content'>hello</div>
                        <slot></slot>
                    </div>`
    });

    Vue.component("my-content2", {
        //props: ["content"],
        template: `<div>
                        <slot name="header">不給該插槽傳值,則顯示我</slot>
                        <div class='content'>hello</div>
                        <slot name="footer"></slot>
                    </div>`
    });

    var vm = new Vue({
        el: "#root"
    })
</script>
</body>
</html>
相關文章
相關標籤/搜索