vue学习【作用域插槽】

<child></child>

Vue.component('child', {
      data: function () {
          return {
              list: [1, 2, 3]
          }
      },
      template: '<div>
                    <ul>
                       <li v-for="item of list">{{item}}</li>
                    </ul>
                 </div>'
})


那么,我们要想让父组件每一次调用子组件时再定义显示方式,也就是说,在子组件中定义好了v-for循环了list,具体怎么显示,由父组件告诉我。那么在子组件中定义一个slot插槽,在父组件中添加一个作用域插槽【需要用template包裹】,在其内写显示的样式。

父组件需要得到子组件数据时,就需要template标签。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>vue中作用域插槽</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
    <child>
        <template slot-scope="props">
            <li>{{props.item}}</li><!--我想渲染成列表形式-->
        </template>
    </child>
</div>
</body>
</html>
<script>
    Vue.component('child', {
        data: function () {
            return {
                list: [1, 2, 3]
            }
        },
        template: '<div><ul><slot v-for="item of list" :item="item">{{item}}</slot></ul></div>'
    })

    var vm = new Vue({
        el: '#app'
    })
</script>

猜你喜欢

转载自blog.csdn.net/qq_33866063/article/details/89669582