簡單通信
父—>子
1.父組件綁定自定義屬性
2.子組件props接收
3.子組件任意使用
子—>父
1.父組件綁定自定義方法
2.子組件 $emit(‘事件名’, value) 觸發
3.傳入父組件
<!--
* @Author: your name
* @Date: 2020-03-31 19:50:40
* @LastEditTime: 2020-03-31 20:17:31
* @LastEditors: Please set LastEditors
* @Description: 父子組件的簡單通信
* @FilePath: \x\06.html
-->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
<script type="text/javascript" src="./node_modules/vue/dist/vue.js"></script>
<script type="text/javascript">
// 全局組件的創建
// 第一個是組件名,第二個是配置選項
// 子傳父
// 1.在父組件綁定自定義事件
// 2.子組件觸發$emit()
Vue.component('Child', {
template: '<div><p>I am child</p>\
<input type="text" v-model="childData" @input="changeValue(childData)"></div>',
props: ["childData"],
methods: {
changeValue(val) {
// 自定義事件一定通過 $emit 去觸發
// $emit(自定義的事件名。消息)
this.$emit('childHander', val)
}
},
})
// 父傳子
// 1.先給父組件綁定自定義屬性
// 2.子組件props接收數據,可以在子組件任意使用
Vue.component('Parent', {
data() {
return {
msg: 'father msg'
}
},
template: '<div><Child :childData="msg" @childHander="childHander" /></div>',
methods: {
childHander(val) {
console.log(val)
}
},
})
// 局部組件
var App = {
data() {
return {
}
},
methods: {
clickButton(e) {
console.log(this)
}
},
components: {},
template: '<Parent />'
};
console.log(App)
var vm = new Vue({
el: "#app",
data() {
return {
}
},
// 掛載子組件
components: {
App
},
// 父組件可以直接使用
template: '\
<App></App>\
'
});
console.log(vm)
</script>
</body>
</html>