Vue:作用域插槽的使用方法

基本语法:
在这里插入图片描述


代码案例:(解析在注释中)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./js/vue.js"></script>
    <title>Document</title>
    <style>
        .current {
            color: orange;
        }
    </style>
</head>

<body>
    <div id="app">
        <fruit-list :fruits="fruits">
            <template v-slot="slotProps">
                <!--slotProps是固定的名字 不能改变 接受子组件传递过来的数据-->
                <!--  slot-scope已经废弃 不建议使用 新增v-slot  -->
               <strong v-if="slotProps.info.id==2"  class="current">{{slotProps.info.name}}</strong>
               <span v-else>{{slotProps.info.name}}</span>
            </template>
        </fruit-list>
    </div>
    <script>
        Vue.component('fruit-list', {
            props: ['fruits'],
            template: `
            <ul>
            <li v-for="fruit in fruits" :key="fruit.id">
                <!--通过插槽储存fruit-->
            <slot :info='fruit'>{{fruit}}</slot>
            <!-- :info其实就是 v-bind:info-->
            </li>
            </ul>
            `
        })
        var vm = new Vue({
            el: '#app',
            data: {
                fruits: [{
                    id: 1,
                    name: 'apple'
                }, {
                    id: 2,
                    name: 'orange'
                }, {
                    id: 3,
                    name: 'banana'
                }]
            }
        })
    </script>
</body>

</html>

运行结果:

在这里插入图片描述

发布了28 篇原创文章 · 获赞 7 · 访问量 1179

猜你喜欢

转载自blog.csdn.net/haduwi/article/details/105186634