vue 自定義組件

<!DOCTYPE html>
<html lang="en">
<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>
      <!-- 什麼是組件? 擁有專屬的HTML,CSS,JS和數據的頁面獨立區域
           爲何?重用
           什麼時候用?只要發現頁面中有一個區域可能被反覆使用,都要定義成組件

           建立:每一個組件都是一個縮微的 new Vue()
           使用組件:組件在html中其實就是一個可重用的標籤而已。組件名就是就是標籤名。因此組件起名不要駝峯命名!由於HTML標籤不區分大小寫。可用-分隔多個單詞
            new Vue()必須寫,由於是new Vue掃描頁面時,發現不認識的標籤,纔會去加載自定義的組件
            加載時:會用組件的template中的HTML模板片斷,代替不認識的標籤。
            template必須有一個父元素包裹

           Vue.conponent('組件名',{
                 tempalte:``,                模板,放着html片斷
                 data(){
                     return {//調用一次data(),返回一個新的return
                           //模型變量
                     }
                 },
                 methods:{},
                 watch:{  },
                 computed:{},
                 created(){},
                 mounted(){},
           })
            new Vue({
               el:"#app"
         })   

      -->

      <!-- 自定義組件 -->
      <div id="app">
            <counter></counter><br>
            <counter></counter><br>
            <counter></counter><br>
      </div>
      <script src="vue2.js"></script>

      <script>
   
       Vue.component('counter',{
            template:`<div>  <button @click=change(-1)>-</button><span>{{n}}</span><button @click=change(+1)>+</button> </div>`,
            data(){
                  return{
                        n:1
                  }
            },
            methods:{
                  change(i){
                        this.n+=i
                  }
            }
      })

      new Vue({
            el:"#app"
       })   
      </script>

</body>
</html>
相關文章
相關標籤/搜索