for(let i=0;i<this.$children.length;i++){
console.log(this.$children[i].msg);输出子组件的msg数据;
}
<template id="parentcomponent">
<div >
<p>this is a parent-component</p>
<firstchild ref="f1"></firstchild>
<secondchild ref="f2"></secondchild>
<button @click='show_child_of_parents'>show child msg</button>
</div>
</template>
<script type="text/x-template" id="childOne">
<div>
<p>this is first child</p>
//使用stop阻止默认事件(vue的事件处理机制)
<button @click.stop='getParent'>get parent msg</button>
</div>
</script>
<template id="childSec">
<div>
<p>this is second child</p>
</div>
</template>
<script>
new Vue({
el:"#app",
data:{},
components:{
"parent-component":{
template:'#parentcomponent',
data(){
return{msg:'这是父组件中的内容'}
},
methods:{
show_child_of_parents(){
//children方式访问自组件
for(let i=0;i<this.$children.length;i++){
console.log(this.$children[i].msg);
}
//通过$ref打标记,访问子组件
console.log(this.$refs.f1.msg);
this.$refs.f1.getParent();
},
},
components:{
'firstchild':{
template:'#childOne',
data(){
return {msg:'这是第一个子组件'};
},
methods:{
getParent(){
let a=1;
console.log(a);
alert(this.$parent.msg);
}
},
},
'secondchild':{
template:'#childSec',
data(){
return {msg:"这是第二个组件"};
}
}
}
}
}
});
</script>
<body>
<p><strong>可以通过$refs访问父组件的子组件</strong></p>
<div id="app">
<parent-component></parent-component>
</div>
</body>
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有