vue中的scope使⽤详解
我们都知道vue slot插槽可以传递任何属性或html元素,但是在调⽤组件的页⾯中我们可以使⽤template scope="props"来获取插槽上的属性值,获取到的值是⼀个对象。
注意:scope="它可以取任意字符串";
上⾯已经说了 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>姓名:{{w.name}}</p>
<p>年龄: {{w.age}}</p>
<p>性别: {{w.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 代码如下:
Vueponent('tb-list', {
template: '#tb-list',
props: {
data: {
type: Array,
required: true
}
},
data() {
return {
}
},
beforeMount() {
},
mounted() {
},
methods: {
}
});
上⾯代码我们注册了⼀个叫 tb-list 这么⼀个组件,然后给 tb-list 传递了⼀个data属性值;该值是⼀个数组,如下值:
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组件中的任何内容;其内容如下:
<template scope="scope">
<div class="info" :s="JSON.stringify(scope)">
<p>姓名:{{w.name}}</p>
<p>年龄: {{w.age}}</p>
<p>性别: {{w.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标签上返回的所有属性值,并且是⼀个对象的形式保存起来,该slot有两个属性,⼀个是row,另⼀个是$index, 因此返回 {"row": item, "$index": "index索引"}; 其中item就是data⾥⾯的⼀个个对象。
vue json字符串转数组
最后页⾯被渲染成如下页⾯;
总结
以上所述是⼩编给⼤家介绍的vue中的scope使⽤详解,希望对⼤家有所帮助,如果⼤家有任何疑问欢迎给我留⾔!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。