Vue父组件主动获取子组件的值和方法 |
您所在的位置:网站首页 › vue父组件获取子组件元素 › Vue父组件主动获取子组件的值和方法 |
在父组件使用子组件的代码中,为子组件加上ref="name(自己设置一个名称)" 然后在代码中: this.$refs.name(你设置的名字).data //获取子组件data中的数据 this.$refs.name(你设置的名字).method() //获取子组件中method中的方法!!!注意:如果父组件以循环的方式生成子组件,如: 则this.$refs.name(你设置的名字)将会是一个VueComponent数组,这时候可以先获取数组的长度,再依次遍历: for(let i=0; i data: () => ({}), components:{ 'my_component':child_component }, methods:{ get_data_from_child_component(){ this.$refs.child_component.whatever() //父组件调用子组件的方法 console.log(this.$refs.child_component.msg) //父组件调用子组件的值 } }, mounted(){ this.get_data_from_child_component() }, };子组件代码: export default { data: () => ({ msg:"这是子组件的值", }), methods:{ whatever(){ alert("这是子组件的方法") } } }; |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |