您的位置:首页 > 产品设计 > UI/UE

vue2.0+基础知识连载(15)--- 父子组件通信

2018-01-20 19:14 483 查看
<!DOCTYPE html>
<html>

<head>
<title>vue2.0+基础知识连载(15)--- 父子组件通信</title>
</head>

<body>

<h3>vue2.0+基础知识连载(15)--- 父子组件通信</h3>

<div id='app'>
<father></father>
</div>

<!-- 模板 -->
<template id="father">
<div>
<h3>{{name}}</h3>
<p>群消息girl:</p>
<div>
{{somebody}} 说: 我 {{age}} 了。
</div>
<hr>
<child :girls="aGirls" :noticeGirl="noticeGirl" @introduce="introduceSelf"></child>
</div>
</template>

<template id="child">
<div>
<h5>{{name}}</h5>
<div>
<ul>
<li v-for="(value, index) in girls">
{{index}} - {{value.name}} - {{value.age}}
<button @click="noticeGroup(value.name, value.age)">发送消息</button>
</li>
</ul>
</div>
<div v-if='noticeGirl'>接收来自大群的消息:{{noticeGirl}}</div>
<div v-else>暂无来自大群的消息</div>
</div>
</template>

<script src="https://cdn.bootcss.com/vue/2.5.8/vue.min.js"></script>
<script type="text/javascript">

// 定义组件
var FATHER = {
template: "#father",
data: function() {
return {
name: '这是父组件',
aGirls: [
{name: '小丽', age: 22},
{name: '小美', age: 21},
{name: '小荷', age: 24}
],
somebody: '',
age: '',
noticeGirl: ''
}
},
methods: {
introduceSelf: function(opt) {
this.somebody = opt.name;
this.age = opt.age;

// 通知girl收到消息
this.noticeGirl = opt.name + ',已收到消息';
}
},
components: {
'child': {
template: "#child",
data: function() {
return {
name: '子组件',
}
},
methods: {
noticeGroup(name, age) {
var emitData = {
name: name,
age: age
};
this.$emit('introduce', emitData);
},
},
props: {
girls: {
type: Array,
required: true
},
noticeGirl: {
type: String,
required: false
}
}
}
}
};

// 注册组件
Vue.component('f>   ther', FATHER);

var vm = new Vue({
data: {},
}).$mount('#app');
</script>
</body>

</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  vue 父子组件通信