Vue 組件學(xué)習(xí)筆記
局部組件的使用
簡易 demo
<div id="app"></div>
<script>
// 1. 聲明子組件
var Vheader = {
template: '<div>我是頭部組件</div>'
}
var App = {
template: '<div>我是入口組件</div>'
}
new Vue({
el: '#app',
data() {
return {}
},
// 2. 掛載子組件
components: {
App
},
// 3. 使用子組件
template: '<App/>'
})
</script>
組件通信
總結(jié):
- 子組件通過 props 接受父組件的數(shù)據(jù)
- 子組件通過$emit 觸發(fā)父組件的自定義事件來向父組件傳遞數(shù)據(jù)
組件通信:子 => 父 demo
Vue.js 的文件路徑記得修改
- 先給父組件中綁定自定義屬性
- 在子組件中使用 props 接收父組件傳遞的數(shù)據(jù)
- 可以在子組件中任意使用
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>組件通信-通過prop往子組件通信</title>
<script type="text/javascript" src="JS/Vue.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/javascript">
// 2. Child組件
var Child = {
template: `
<div>
<p>我是一個(gè)子組件:{{ childData }}</p>
<input type="text" v-model='childData' />
</div>
`,
props: ['childData']
}
// 1. Parent組件
var Parent = {
data() {
return {
msg: '我是父組件的數(shù)據(jù)'
}
},
template: `
<div>
<p>我是一個(gè)父組件</p>
<Child :childData='msg'/>
</div>
`,
components: {
Child
}
}
var App = {
data() {
return {}
},
template: `
<div>
<Parent/>
</div>
`,
components: {
Parent
}
}
new Vue({
el: '#app',
data() {
return {}
},
components: {
App
},
template: `
<App/> `
})
</script>
</body>
</html>
組件通信:父 => 子 demo
- 在父組件綁定
自定義的事件 - 在子組件中觸發(fā)原生的事件,在函數(shù)中使用$emit 觸發(fā)自定義的事件(childHandler)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>通過事件向子組件通信</title>
<script type="text/javascript" src="JS/Vue.js"></script>
</head>
<body>
<div id="app"></div>
<script type="text/javascript">
// Child組件
var Child = {
template: `
<div>
<p>我是一個(gè)子組件:{{ childData }}</p>
<input type="text" v-model='childData' @input='changeValue(childData)' /> // v-model改變傳遞的數(shù)據(jù)會(huì)報(bào)warn,本例只是演示,不必顧慮
</div>
`,
methods: {
changeValue(val) {
// 在函數(shù)中
// $emit(自定義的事件名,傳遞的 消息)
// 自定義的事件一定通過this.$emit去觸發(fā)
this.$emit('childHandler', val)
}
},
props: ['childData']
}
// Parent組件
var Parent = {
data() {
return {
msg: '我是父組件的數(shù)據(jù)'
}
},
// childHandler為父組件綁定的自定義事件(步驟1),@是v-on的縮寫,用于監(jiān)聽事件
template: `
<div>
<p>我是一個(gè)父組件</p>
<Child :childData='msg' @childHandler='childHandler'/>
</div>
`,
methods: {
childHandler(val) {
console.log(val)
}
},
components: {
Child
}
}
var App = {
data() {
return {}
},
template: `
<div>
<Parent/>
</div>
`,
components: {
Parent
}
}
new Vue({
el: '#app',
data() {
return {}
},
components: {
App
},
template: `
<App/>
`
})
</script>
</body>
</html>
最后小結(jié):在本例中,父組件上為子組件綁定 childHandler 方法,子組件綁定 changeValue 方法,而在 changeValue 方法中,使用 this.$emit()向父組件的方法 childHandler 傳遞數(shù)據(jù),即完成了父子組件之間的通信。