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">
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
<title>Document</title>
</head>
<body>
<div id="app">
   hellow 
    </div>
<script>
	new Vue({
		el : "#app",
		template : "<div>{{msg}}</div>",
		data : {
			
				msg : "你好!"
			
		}
	})

</script>
</body>
</html>

template 屬性中的 字符串標籤 會替換   id 爲 app 的 標籤     ,在template 中可以使用  {{  }}  的方式  調用自己的屬性  如msg

 

示例:

 

template 優缺點  ,寫字符串html 沒有編輯器的智能提示  ,編寫daim效率低 

 

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">
    <script src="https://unpkg.com/[email protected]/dist/vue.js"></script>
    <title>Document</title>
</head>
<body>
    <div id="app">
    <my-component></my-component>
  
    </div>
    <script>
    Vue.component('my-component',{
        template : `<div>
            <button @click= "clickMe">{{count}}</button>
        </div>`,
        data : function(){
            return {
                count : 0 
            }
        },
        methods : {
            clickMe : function(){
               this.count ++;
            }
        }
    })

new Vue({
    el : '#app',

})


    </script>
</body>
</html>

示例:

需要注意 在 component 函數中  data 是  函數形式的  ,這是爲了避免 多個地方都調用該組件時, 數據都是同一個

 

這種情況是可以模擬的 : 如下 :

        
     var data = {
                count : count
            }

    Vue.component('my-component',{
        template : `<div>
            <button @click= "clickMe">{{count}}</button>
        </div>`,
        data : function(){
            return data
        },
        methods : {
            clickMe : function(){
               this.count ++;
            }
        }
    })

new Vue({
    el : '#app',

})

效果:

 

局部組件的定義 :   這樣定義出來的組件只有  #app  可以使用  my-component 組件,

var myConponent = {
        template : `<div>
            <button @click= "clickMe">{{count}}</button>
        </div>`,
        data : function(){
            return data
        },
        methods : {
            clickMe : function(){
               this.count ++;
            }
        }
    }
   // Vue.component('my-component',myConponent)

new Vue({
    el : '#app',
    components : {
        'my-component' : myConponent
    }

})

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章