Vue.js 父子组件通讯开发实例

2020-06-16 06:34:28易采站长站整理

</div>
</div>
<div class="box clearfix">
<label for="" class="box-left">爱好:</label>
<div class="bor-right">
<input type="text" v-model="inst">
</div>
</div>
<div class="box clearfix">
<label for="" class="box-left"> </label>
<div class="bor-right">
<a href="javascrip:;" @click="add_table">添加</a>
</div>
</div>
<h3>下面的表格是子组件信息:</h3>
<!-- 把父组件的table_data数据绑定到子组件上 -->
<broadcase :data="table_data"></broadcase>
</section>
<template id="broadcase">
<div class="table">
<table>
<thead>
<tr>
<th>id</th>
<th>姓名</th>
<th>爱好</th>
</tr>
</thead>
<tbody>
<tr v-for="list in data">
<td>{{ list.id }}</td>
<td>{{ list.name }}</td>
<td>{{ list.inst }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
Vue.component('broadcase',{ //这里直接使用了注册组件的语法糖的方式注册,简单快捷
template: '#broadcase',
props: ['data'], // props是用来接受父组件的传递参数,也可在里面自定义数据,如果数据需要有默认值的话,需在data里面定义
data: function() {
return {
msg : 'abc'
}
},
events : { //这里只是个例子,子组件监听父组件的数据变化
test : function(msg){
console.log(msg);
}
},
methods: {
}
});
var mvvm = new Vue({
el: '#app',
data: {
table_data: [
{
id: 1,
name: 'gjei',
inst: 'gjweir'
},{
id: 2,
name: 'jiuyer',
inst: 'oiuyt'
}
]},
methods: {
add_table: function(){
var set = {
id: this.id,
name: this.name,
inst : this.inst
};
this.table_data.push(set);
// this.$broadcast('test', set); //这里,只是一个例子语法
this.id = '';
this.name = '';
this.inst = '';
}
}
});
</script>

上处举的两个例子,都可以点击这里测试,文件已经上传个人空间 vue父子组件通讯demo

当写到这里的时候,回头看了一下,自己写的内容,貌似写得有点乱,真是汗颜啊!很久之前就想过写博客,建立自己的笔记库,只是以前尝试写的时候,真是无法下手如何去写,最近,下定决心,不管写的怎么样,也坚持去写,万一哪天自己的文笔突然变得好起来了呢!

vue父子组件通讯,其实应用并不是很难,它其实也是提供了相应的api接口监听,实际的项目应用该如何操作变化,还是得需要我们自己写,重点,还是得要提高我们的js水平,毕竟,复杂的web应用越来越多!希望,喜欢前端的同学们都能在js的路上共勉.