父组件访问子组件
有时候我们需要父组件直接访问子组件,子组件直接访问父组件,或者是子组件访问跟组件。
- 父组件访问子组件:使用$children或refs
- 子组件访问父组件:使用$parent
代码
<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="author" content="xiaonaihu" /><meta name="generator" content="HBuilder X" /><title>父组件访问子组件</title><script src="../../lib/vue.js" type="text/javascript" charset="utf-8"></script></head><body><div id="app"><cpn></cpn><cpn></cpn><button @click = "btnClick">Button</button></div><template id="cpn"><div>children component</div></template><script type="text/javascript">const app = new Vue({el:"#app",data:{message:"hello vue!"},methods:{btnClick(){console.log(this.$children);this.$children[0].showMessage();// 父组件直接访问子组件中的showMessage方法// this.$children返回一个数组}},components:{cpn:{template:"#cpn",methods:{showMessage(){console.log('showMessage');}}}}});</script></body>
</html>
通过this.children的缺陷在于需要通过指定数组下标去访问指定子组件中的方法或属性,所以在开发中通常会使用$refs来访问子组件:
父组件中通过this.$refs.ref属性名来访问子组件
代码
<!DOCTYPE html>
<html><head><meta charset="utf-8"><meta name="author" content="xiaonaihu" /><meta name="generator" content="HBuilder X" /><title>父组件访问子组件</title><script src="../../lib/vue.js" type="text/javascript" charset="utf-8"></script></head><body><div id="app"><cpn></cpn><cpn></cpn><cpn ref = "aa"></cpn><button @click = "btnClick">Button</button></div><template id="cpn"><div>children component</div></template><script type="text/javascript">const app = new Vue({el:"#app",data:{message:"hello vue!"},methods:{btnClick(){console.log(this.$children);// this.$children[0].showMessage();this.$refs.aa.showMessage();// 父组件直接访问子组件中的showMessage方法// this.$children返回一个数组}},components:{cpn:{template:"#cpn",methods:{showMessage(){console.log('showMessage');}}}}});</script></body>
</html>