理解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" />
- <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属性值;该值是一个数组,如下值:
- 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>姓名:{{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标签上返回的所有属性值,并且是一个对象的形式保存起来,该slot有两个属性,一个是row,另一个是$index, 因此返回 {"row": item, "$index": "index索引"}; 其中item就是data里面的一个个对象。
最后页面被渲染成如下页面;
查看页面效果;
来源: http://www.cnblogs.com/tugenhua0707/p/7745735.html