创建vue模板
<template>
<div>
<button @click="handleClick"> 点我啊 </button>
</div>
</template>
<script>
export default {
name: 'child',
data() {
return {
returnData: '洞拐洞拐,我是子类传回的数据'
}
},
methods: {
handleClick() {
console.log('点击了子类的点击');
// 模板点击事件回调使用 this.$emit('父模板绑定事件','子模板回传数据')
this.$emit('childClick',this.returnData)
}
}
}
</script>
<style scoped>
</style>
父模板
<template>
<div class="hello">
{{msg}}
<child-view @childClick="handleChild"></child-view>
</div>
</template>
<script>
import child from './Child' // 导入模板
export default {
name: 'HelloWorld',
components: {
ChildView: child // 定义模板
},
data () {
return {
msg: 'Welcome to Your Vue.js App'
}
},
methods: {
handleChild(str) { // 父模板回调子模板
console.log('子控件回传数据'+str);
alert('子控件回传数据'+str)
}
}
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>
模板传值
<child-view @childClick="handleChild" :data="111"></child-view>
// 子控件使用该值
{{data}}
props: ['data'], // 该方法相当于是已经设置了data(){return {data:''}}
// 或
props: {
data:[Number,String,Object] // 限制传值类型
}
slot
slot可以将父模板的代码插入到子模板中
// 父模板
<child-view @childClick="handleChild" :data="inputData">
<p>哈哈,我是slot代码</p>
<p slot="msg">我是消息</p>
</child-view>
// 子模板
<div>
<slot>empty</slot>
<slot name="msg">no msg</slot>
</div>