1. 程式人生 > 程式設計 >Vue作用域插槽實現方法及作用詳解

Vue作用域插槽實現方法及作用詳解

預設插槽和具名插槽的概念比較好理解,這裡主要以官方文件的案例來講解一下作用域插槽。

首先是有一個currentUser的元件:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <div id="app">
    <current-user>
      {{ user.firstName }}
    </current-user>
  </div>
  <script src="vue.min.js"></script>
  <script>
    Vue.component('currentUser',{
      template: `
        <span>
          <slot>{{ user.lastName }}</slot>
        </span>
      `,data() {
        return {
          user: {
            firstName: 'w',lastName: 'ts'
          }
        }
      }
    })

    new Vue({
      el: '#app'
    })
  </script>
</body>
</html>

然而該頁面無法正常工作,因為只有currentUser可以訪問到user,出錯的地方在這裡:

Vue作用域插槽實現方法及作用詳解

然後,引入一個插槽prop:

<span>
  <slot :user="user">
    {{ user.lastName }}
  </slot>
</span>

接著,需要給v-slot帶一個值來定義我們提供的插槽 prop 的名字:

<current-user>
  <template v-slot="wts">
    {{ wts.user.firstName }}
  </template>
</current-user>

簡單的講作用域插槽就是讓插槽內容能夠訪問子元件中才有的資料,修改後便可以正常工作了。

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。