一、Vue父组件调用子组件方法(组件通讯)
利用ref:
//父组件 <template> <div class="home"> <HelloWorld ref="mychild"></HelloWorld> <div @click="clickParent">click me</div> </div> </template> <script> import HelloWorld from '@/components/HelloWorld.vue' export default { name: 'home', components: { HelloWorld }, methods: { clickParent() { this.$refs.mychild.parentHandleclick("嘿嘿嘿"); } } } </script> //子组件 <template> <div class="hello"> <h1>我是HelloWorld组件</h1> </div> </template> <script> export default { name: 'HelloWorld', created() { }, methods: { parentHandleclick(e) { console.log(e) } } } </script>
2.$emit $on方法
//父组件中 <template> <div> <Button @click="handleClick">点击调用子组件方法</Button> <Child ref="child"/> </div> </template> <script> import Child from './child'; export default { methods: { handleClick() { this.$refs.child.$emit("childmethod") //子组件$on中的名字 }, }, } </script> //子组件中 <template> <div>我是子组件</div> </template> <script> export default { mounted() { this.$nextTick(function() { this.$on('childmethods', function() { console.log('我是子组件方法'); }); }); }, }; </script>