Vue2.x 父子组件之间的相互访问

儿子对爹说:“爹!你的车今天我开了”

  • 父访问子用$children
  • 子访问父用$parent
  • 父访问子更推荐用$refs
  • 因为$children是带下标值的,所以一旦这个结构发生变化,没办法动态的更改下标值,不推荐使用这个方法

父访问子

  • 先创建父子关系
<div id="father">
	<h1>{
    
    {
    
    name}}</h1>
	<button>我要调用我的儿子的方法</button>
	<son></son>
</div>

<template id="son">
	<div>
		<h2>{
    
    {
    
    name}}</h2>
		<h2>{
    
    {
    
    message}}</h2>
	</div>
</template>
const son = {
    
    
  template:'#son',
  data() {
    
    
    return {
    
    
      name:'我是儿子',
      message:''
    }
  },
  methods:{
    
    
    showMessage() {
    
    
      console.log('我被我爹调用了')
      this.message = '我被我爹调用了'
    }
  }
}
		
const father = new Vue({
    
    
  el:'#father',
  data:{
    
    
    name:'我是爹'
  },
  components:{
    
    
	son
  }
})

看一下页面效果
点击按钮,会调用儿子上的showMessage方法
在这里插入图片描述

  • 给儿子标签打上印记
  • 给按钮绑定事件
  • ref和$refs是一对儿,ref用来给标签打上标记
<div id="father">
	<h1>{
    
    {
    
    name}}</h1>
	<button @click="btnClick">我要调用我的儿子的方法</button>
	<son ref='son'></son>
</div>
  • $refs.son用来选中那个被打上son印记的标签
  • 更准确的来说是那一个组件(vueComponent实例)
const father = new Vue({
    
    
    //。。。
	methods:{
    
    
		btnClick() {
    
    
			console.log(this.$refs.son)
			this.$refs.son.showMessage()
		}
	},
})

看一下页面效果
在这里插入图片描述

子访问父

  • $parent
  • $root访问祖宗
  • 实际开发不建议这样使用,因为这样做,子组件就不够独立了,换个地方这个子组件的爹就不一样了,有可能没有目标属性
  • 组件化开发本身就是提高复用性,和父组件之间的耦合度太高了

给爹添加一个供儿子使用的数据

const father = new Vue({
    
    
	el:'#father',
	data:{
    
    
		name:'我是爹',
		fatherMes:'我将给我儿子'
	},
	//。。。。
})

给儿子添加一个按钮点击调用爹的数据

<template id="son">
	<div>
		<h2>{
    
    {
    
    name}}</h2>
		<h2>{
    
    {
    
    message}}</h2>
		<button @click="callFather">调用我爹地数据</button>
	</div>
</template>

添加事件

const son = {
    
    
// 。。。。
	methods:{
    
    
	//。。。。
		callFather() {
    
    
			console.log(this.$parent)
			console.log(this.$parent.fatherMes);
		}
	}
}

查看页面效果
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_47883103/article/details/108313691