在Vue中使用插槽

以下方法传值存在两个问题:
1.不能去掉外面包裹的标签
2.如果要传值的太多,这种方法很搓很难阅读

<!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>

那用啥方法?用插槽啊!
插槽的使用细节:

<!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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章