vue中的scope使用詳解
我們都知道vue slot插槽可以傳遞任何屬性或html元素,但是在調(diào)用組件的頁面中我們可以使用 template scope="props"
來獲取插槽上的屬性值,獲取到的值是一個對象。
注意:scope="它可以取任意字符串";
上面已經(jīng)說了 scope獲取到的是一個對象,是什么意思呢?我們先來看一個簡單的demo就可以明白了~
如下模板頁面:
<!DOCTYPE html> <html> <head> <title>Vue-scope的理解</title> <script src="./libs/vue.js"></script> <link rel="stylesheet" href="./css/index.css" rel="external nofollow" /> <script src="./js/scope.js"></script> </head> <body> <div id="app"> <tb-list :data="data"> <template scope="scope"> <div class="info" :s="JSON.stringify(scope)"> <p>姓名:{{scope.row.name}}</p> <p>年齡: {{scope.row.age}}</p> <p>性別: {{scope.row.sex}}</p> <p>索引:{{scope.$index}}</p> </div> </template> </tb-list> </div> <script id="tb-list" type="text/x-template"> <ul> <li v-for="(item, index) in data"> <slot :row="item" :$index="index"></slot> </li> </ul> </script> <script type="text/javascript"> new Vue({ el: '#app', data() { return { data: [ { name: 'kongzhi1', age: '29', sex: 'man' }, { name: 'kongzhi2', age: '30', sex: 'woman' } ] } }, methods: { } }); </script> </body> </html>
js 代碼如下:
Vue.component('tb-list', { template: '#tb-list', props: { data: { type: Array, required: true } }, data() { return { } }, beforeMount() { }, mounted() { }, methods: { } });
上面代碼我們注冊了一個叫 tb-list 這么一個組件,然后給 tb-list 傳遞了一個data屬性值;該值是一個數(shù)組,如下值:
data: [ { name: 'kongzhi1', age: '29', sex: 'man' }, { name: 'kongzhi2', age: '30', sex: 'woman' } ]
tb-list組件模板頁面是如下:
<ul> <li v-for="(item, index) in data"> <slot :row="item" :$index="index"></slot> </li> </ul>
遍歷data屬性值,然后使用slot來接收 tb-list組件中的任何內(nèi)容;其內(nèi)容如下:
<template scope="scope"> <div class="info" :s="JSON.stringify(scope)"> <p>姓名:{{scope.row.name}}</p> <p>年齡: {{scope.row.age}}</p> <p>性別: {{scope.row.sex}}</p> <p>索引:{{scope.$index}}</p> </div> </template>
最后在模板上使用scope來接收slot中的屬性;因此scope的值是如下一個對象:
{"row":{"name":"kongzhi1","age":"29","sex":"man"},"$index":0}
因為遍歷了二次,因此還有一個是如下對象;
{"row":{"name":"kongzhi2","age":"30","sex":"woman"},"$index":1}
從上面返回的scope屬性值我們可以看到,scope返回的值是slot標(biāo)簽上返回的所有屬性值,并且是一個對象的形式保存起來,該slot有兩個屬性,一個是row,另一個是$index, 因此返回 {"row": item, "$index": "index索引"}; 其中item就是data里面的一個個對象。
最后頁面被渲染成如下頁面;
總結(jié)
以上所述是小編給大家介紹的vue中的scope使用詳解,希望對大家有所幫助,如果大家有任何疑問歡迎給我留言!
相關(guān)文章
vue.js學(xué)習(xí)筆記之綁定style樣式和class列表
數(shù)據(jù)綁定一個常見需求是操作元素的 class 列表和它的內(nèi)聯(lián)樣式。這篇文章主要介紹了vue.js綁定style和class的相關(guān)資料,需要的朋友可以參考下2016-10-10Vue網(wǎng)絡(luò)請求的三種實現(xiàn)方式介紹
這篇文章主要介紹了Vue網(wǎng)絡(luò)請求的三種實現(xiàn)方式,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-09-09關(guān)于Vue?"__ob__:Observer"屬性的解決方案詳析
在操作數(shù)據(jù)的時候發(fā)現(xiàn),__ob__: Observer這個屬性出現(xiàn)之后,如果單獨拿數(shù)據(jù)的值,就會返回undefined,下面這篇文章主要給大家介紹了關(guān)于Vue?"__ob__:Observer"屬性的解決方案,需要的朋友可以參考下2022-11-11