Vue作用域插槽實現(xiàn)方法及作用詳解
更新時間:2020年07月08日 14:40:49 作者:viewts
這篇文章主要介紹了Vue作用域插槽實現(xiàn)方法及作用詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
默認(rèn)插槽和具名插槽的概念比較好理解,這里主要以官方文檔的案例來講解一下作用域插槽。
首先是有一個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,出錯的地方在這里:

然后,引入一個插槽prop:
<span>
<slot :user="user">
{{ user.lastName }}
</slot>
</span>
接著,需要給v-slot帶一個值來定義我們提供的插槽 prop 的名字:
<current-user>
<template v-slot="wts">
{{ wts.user.firstName }}
</template>
</current-user>
簡單的講作用域插槽就是讓插槽內(nèi)容能夠訪問子組件中才有的數(shù)據(jù),修改后便可以正常工作了。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Vue3后臺管理系統(tǒng)之創(chuàng)建和配置項目
后臺管理系統(tǒng)是我們?nèi)粘i_發(fā)學(xué)習(xí)經(jīng)常遇到的一個項目,下面這篇文章主要給大家介紹了關(guān)于Vue3后臺管理系統(tǒng)之創(chuàng)建和配置項目的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2022-09-09
Vue-Router實現(xiàn)組件間跳轉(zhuǎn)的三種方法
這篇文章主要為大家詳細(xì)介紹了Vue-Router來實現(xiàn)組件間跳轉(zhuǎn)的三種方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-11-11

