vue|vue中用ref实现父子组件、孙组件、兄弟组件、非亲子孙组件互相调用的方法

无论是什么层级的组件之间互相调用,掌握好ref后都是万变不离其宗。来练练手吧
1.父子传: 父组件:

> import Child from './child'; export default { methods: { handleClick() { this.$refs.child.childFun(); }, }, }

子组件:
> export default { methods: { childFun() { console.log('我是子组件的方法'); }, }, };

2.父孙传: 父组件:
> import Child from './child'; export default { components: { Child }, methods: { handleClick() { this.$refs.child.$refs.grandson.test() }, }, }

子组件:
> import grandson from './grandson'; export default { name: "child", components: { grandson }, methods: { childFun() { console.log('我是子组件的方法'); }, }, };

孙组件:
> export default { name: "grandson", methods:{ test(){ console.log('我是孙组件的方法') } }}

3.父孙传2(复用性更高): 父组件:
> import Child from './child'; export default { components: { Child }, methods: { handleClick() { this.$refs.child.test(); }, }, }

子组件:
> import grandson from './grandson'; export default { name: "child", components: { grandson }, methods: { childFun() { console.log('我是子组件的方法'); }, test() { this.$refs.grandson.test(); // 一层层调用到孙组件方法 }, }, };

孙组件:
> export default { name: "grandson", methods:{ test(){ console.log('我是孙组件的方法') } }}

4.兄弟传: 父组件:
> import child1 from './components/child1'; import child2 from './components/child2'; export default { name: 'father', components: { child1, child2 }, methods: { order(){ this.$refs.child1Container.say(); } } }

子兄弟组件1:
> export default { name: 'child1', methods: { say(){ console.log('我是子组件1里面的方法"); } } }

子兄弟组件2:
> export default { name: 'child2', methods: { orderBro(){ this.$emit('order'); } } }

5.非亲子孙传: 【vue|vue中用ref实现父子组件、孙组件、兄弟组件、非亲子孙组件互相调用的方法】父组件:
> import child1 from './components/child1'; import child2 from './components/child2'; export default { name: 'father', components: { child1, child2 }, methods: { order(){ this.$refs.child1Container.say(); } } }

子兄弟组件1:
> export default { name: 'child1', methods: { say(){ this.$refs.grandson.say(); } } }

子兄弟组件2:
> export default { name: 'child2', methods: { orderBroGrandson(){ this.$emit('order'); } } }

子兄弟组件1的子组件(孙组件):
> export default { name: "grandson", methods:{ say(){ console.log('调用子兄弟组件1的子组件(孙组件)的方法') } }}


ref真滴牛弊
THX~

    推荐阅读