組件的使用
<!DOCTYPE html>
<html>
<head>
<title>組件</title>
<script src="Vue.min.js"></script>
<script>
window.onload = () => {
Vue.component('Prise', {
// 模板以及函數
data: function() {
return {
like: 100,
}
},
methods: {
clickLike: function() {
this.like++;
}
},
template: `
<div>
<p>{{ like }}</p>
<button v-on:click="clickLike">clickLike</button>
</div>
`
})
new Vue({
el: '#main',
data: {
message: 'Welcome XKD!',
}
})
}
</script>
</head>
<body>
<diV id="main">
<p>{{ message }}</p>
<Prise></Prise>
</diV>
</body>
</html>
組件的數據傳遞
...
Vue.component('Prise', {
// 定義一個props,它是一個數組
props: ['propsdata', 'dislike'],
data: function() {
return {
like: this.propsdata,
}
},
...
template: `
<div>
<p>{{ like }}</p>
<p>{{ dislike }}</p>
<button v-on:click="clickLike">clickLike</button>
</div>
`
})
...
data: {
message: 'Welcome XKD!',
preLike: 500,
dislike: 10,
}
...
<Prise v-bind:propsdata="preLike" v-bind:dislike="dislike"></Prise>
組件的事件傳遞
$emit(父組件方法, arguments)
...
template:`
<button v-on:click="$emit('propreport',like, 1)">report</button>
`
methods: {
getReport: function(e, number) {
alert(number);
}
}
...
<Prise v-on:propreport="getReport" v-bind:propsdata="preLike" v-bind:dislike="dislike"></Prise>
組件傳遞children
插槽
<slot></slot>
動態組件
<component v-bind:is="currentTabComponent"></component>
currentTabComponent: 當前顯示的組件名稱