理解vue中的scope的使用

龍恩0707發表於2017-10-28

理解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裡面的一個個物件。

最後頁面被渲染成如下頁面;
檢視頁面效果;

相關文章