全局組件
使用 Vue.component(tagName,options)
可以注冊一個全局組件。組件是全局的,即在Vue的任何實例下都可以使用該組件
Vue.component('TodoItem',{
props: ['content'],
template: '<li>{{content}}</li>'
})
局部組件
局部組件用選項對象 components 屬性實現注冊,只能在當前實例中使用該組件
var TodoItem = {
props: ['content'],
template: '<li>{{content}}</li>'
}
var app = new Vue({
el: '#app',
components:{TodoItem},
data: {
list: [],
inputValue:''
},
methods: {
btn: function(){
this.list.push(this.inputValue)
this.inputValue = ''
}
}
})
Ps:實例帶碼
<div id='app'>
<input type="text" v-model='inputValue'>
<button @click='btn'>提交</button>
<ul>
<todo-item v-bind:content='item' //這里采用父組件向子組件傳值
v-for='item in list'>
</todo-item>
</ul>
</div>
父子組件間傳值
<div id="root"> //父 => 子 綁定屬性count
<counter ref='one' :count='3' @change='handleIncrease'></counter>
<counter ref='two' :count='2' @change='handleIncrease'></counter>
<div>{{total}}</div>
</div>
<script>
var counter = {
props: ['count'],
template: '<div @click="handleClick">{{number}}</div>',
data: function () {
return {
number: this.count
}
},
methods: {
handleClick: function () {
this.number++
this.$emit('change', 1) // 子 =>父 綁定事件change
}
}
}
var vm = new Vue({
el: '#root',
data: {
total: 5
},
components: {
counter
},
methods: {
handleIncrease: function (step) {
// this.total += step
this.total = this.$refs.one.number + this.$refs.two.number
}
}
})
</script>
組件參數校驗
<div id="root">
<child :content='123'></child>
</div>
<script>
Vue.component('child', {
props: {
content: {
type: String,
// required: false, 是否要求必須傳遞值
// default: 'ASDCXD', 如果沒有傳值,則默認值為ASDCXD
validator: function() {
return value.length > 5 //對所傳的值進行長度校驗
}
}
},
template: '<div>{{content}}</div>'
})
var vm = new Vue({
el: '#root',
})
</script>
組件使用的一些細節
每個row為一個組件,但tbody內只能是tr,所以使用is,(ul ,select一樣,如果內部子項為一個單獨組件,為了防止bug,使用is)
<div id="root">
<table>
<tbody>
<tr is='row'></tr>
<tr is='row'></tr>
<tr is='row'></tr>
</tbody>
</table>
</div>
<script>
Vue.component('row', {
template: '<tr><td>this is row</td></tr>'
})
var vm = new Vue({
el: '#root'
})
</script>
給組件綁定原生事件
<div id="root">
<child @click.native='handleclick'></child>
</div>