學(xué)習(xí)筆記
Vue 組件
1.通過綁定傳遞數(shù)據(jù)(父組件 ——》 子組件)
<div id="app">
<father></father>
</div>
<template id="father">
<div>
<h1>father:{{ fatherMsg.name }} -- {{ fatherMsg.age }}</h1>
<son :faobj='fatherMsg'></son>
</div>
</template>
<template id="son">
<div>
<input type="button" @click='getFather' value="獲取一個(gè)父親">
<h1>小頭兒子:my father -- {{ faobj.name }} -- {{ faobj.age }}</h1>
</div>
</template>
Vue.component('father', {
template: '#father',
data: function () {
return {
fatherMsg: {
name: '小頭爸爸',
age: '21'
}
}
},
components: {
son: {
template: '#son',
data: function () {
return {
fobj: {
name: '',
age: ''
}
}
},
props: ['faobj'],
methods: {
getFather() {
this.fobj = this.faobj
}
}
}
}
})
new Vue({
el: "#app",
})
2.通過事件傳遞數(shù)據(jù) (子組件 ——》 父組件)
<div class="app">
<father></father>
</div>
<template id="father">
<div>
<h1>father: mySon -- {{ sonObj.name }} -- {{ sonObj.age }}</h1>
<son @stof='getSon'></son>
</div>
</template>
<template id="son">
<div>
<h1>son: {{ sobj.name }} -- {{ sobj.age }}</h1>
<input type="button" value="投入到父親的懷抱" @click='sonToFather'>
</div>
</template>
Vue.component('father', {
template: '#father',
data: function () {
return {
sonObj: {
name: '',
age: ''
}
}
},
methods: {
getSon(son) {
this.sonObj = son
}
},
components: {
son: {
template: '#son',
data: function () {
return {
sobj: {
name: '大耳朵圖圖',
age: '1'
}
}
},
methods: {
sonToFather() {
this.$emit('stof', this.sobj)
}
}
}
}
})
new Vue({
el: ".app",
})