使用场景:父组件获取子组件的数据,并且可以更改子组件数据
HTML
<body>
<div id="app">
<div class="titSty">{{title}}</div>
<button @click="putChildData">获取子组件数据</button>
<my-component :name="myname" @changeevent="handleEvent" ref="childData"></my-component>
</div>
</body>
JS
<script>
Vue.component('myComponent', {
template: `
<div id="myCom" style="background-color:yellow;width:200px;height:50px">
{{name}}
<input v-model="emitText" @change="handleChange"/>
</div>
`,
data() {
return {
emitText: '娃哈哈'
}
},
props: ['name'],
methods: {
handleChange() {
this.$emit('changeevent', this.emitText)
}
}
})
const vm = new Vue({
el: '#app',
data: {
myname: '张三',
title: '我是父组件'
},
methods: {
handleEvent(data) {
console.log(data)
},
putChildData() {
this.$refs.childData.emitText = "通过父组件控制子组件数据"
}
}
});
</script>