1.父组件

<template>
  <div class="Parent" ref="Parent">
    <el-button @click="Responsive">父组件执行方法</el-button>
    <Subcomponents></Subcomponents>
  </div>
</template>

<script lang="ts">
import { defineComponent, onMounted,reactive,provide,ref} from 'vue';
import Subcomponents from "@/components/Subcomponents.vue"
export default defineComponent({
  name: 'Parent',
  components:{
    Subcomponents
  },
  setup(props,ctx){
  //响应式数据
  const state = reactive({
    name:"小陈"
  })
  //调用此方法之后,会动态的改变其子孙组件的所有引用值
  const Responsive=()=>{
    state.name="小魔"
  }
  //子组件执行父组件的方法
  const ResponsiveSub=()=>{
    state.name="小锋"
    console.log("我是子组件访问了父节点")
    console.log(Parent.value)
  }
  //孙组件执行父组件的方法
  const ResponsiveSun=()=>{
    state.name="小夏"
    console.log("我是孙组件访问了父节点")
    console.log(Parent.value)
  }
  //父组件数据传递给孙子组件
  provide("ParentValue",state)
  //父组件数据的方法传递给孙子组件,然后孙子组件调用之后直接修改父组件的值
  provide("ResponsiveSub",ResponsiveSub)
  provide("ResponsiveSun",ResponsiveSun)
  onMounted(async () => {
   
  })
  return{
    state,
    Responsive,
    ResponsiveSub,
    ResponsiveSun,
  }
  },
  props: {
    
  },
});
</script>

2.子组件

<template>
  <div class="Subcomponents">
    <p>{{ParentValue.name}}</p>
    <el-button @click="ResponsiveSub">子组件执行父组件方法</el-button>
    <Suncomponent></Suncomponent>
  </div>
</template>

<script lang="ts">
import { defineComponent,onMounted,reactive,inject} from 'vue';
import Suncomponent from "@/components/Suncomponent.vue"
export default defineComponent({
  name: 'Subcomponents',
  components:{
    Suncomponent,
  },
  setup(props,context){
    
  const state = reactive({
    
  })
  const ParentValue = inject("ParentValue")
  const ResponsiveSub = inject("ResponsiveSub")
  onMounted(async () => {
    // props.Deom()

  })
  return{
    ParentValue,
    ResponsiveSub
  }
  },
  props: {
    
  },
});
</script>

3.孙组件

<template>
  <div class="Suncomponent">
    <p>{{ParentValue.name}}</p>
    <el-button @click="ResponsiveSun">孙组件执行父组件方法</el-button>
  </div>
</template>

<script lang="ts">
import { defineComponent,onMounted,reactive,inject} from 'vue';

export default defineComponent({
  name: 'Suncomponent',
  components:{
    
  },
  emits: {
    Error: val => {
      console.log(val);
      return true;
    }
  },
  setup(props){
  const state = reactive({
    
  })
  const ParentValue = inject("ParentValue")
  const ResponsiveSun = inject("ResponsiveSun")
  onMounted(async () => {

  })
  return{
    ParentValue,
    ResponsiveSun
  }
  },
  props: {
    
  },
});
</script>

总结:首先执行父组件的Responsive方法,会出现
在这里插入图片描述
然后执行子组件的ResponsiveSub方法,会出现
在这里插入图片描述
最后执行孙组件的ResponsiveSun方法,会出现
在这里插入图片描述
以上三个方法都是改变了父组件的name的值,并且都是实时响应,对应的子组件里面的值也发生了改变。
最主要的就是使用了vue的provide/inject的属性来实现的.

Logo

前往低代码交流专区

更多推荐