跨多层传值,孙父组件传值

重点是$ listeners,$ attrs
孙组件中能直接触发test的原因在于 父组件调用孙组件时 使用 v-on 绑定了$ listeners 属性
通过v-bind 绑定$ attrs属性,孙组件可以直接获取到父组件中传递下来的props(除了子组件中props声明的)

父组件

<template>
  <div id="app">
     <Son @test="getValue($event)" :text2='hello'/>
  </div>
</template>
 
<script>
import Son from '../components/Son'
export default {
     
     
  name: 'App',
  components: {
     
     
    Son
  },
  data(){
     
     
    return {
     
     
      hello:"hello"
    }
  },
  methods: {
     
     
    getValue(val){
     
     
      console.log('这里是父组件',val);  // val就是孙组件传过来的
      this.hello = val
    }
  },
}
</script>

子组件

<template>
  <div>
    <GrandSon v-on="$listeners" v-bind="$attrs" />
  </div>
</template>

<script>
import GrandSon from "./GrandSon ";
export default {
     
     
  props: ["text2"],
  components: {
     
     
    GrandSon,
  },
  mounted(){
     
     
      console.log('这里是子组件',this.text2);
  }
};
</script>

孙组件

<template>
  <div>
    <button @click="trans()">传值</button>
  </div>
</template>
<script>
export default {
     
     
  data() {
     
     
    return {
     
     
      cdata: "孙组件",
    };
  },
  methods: {
     
     
    trans() {
     
     
      this.$emit("test", this.cdata); // 看这
    },
  },
};
</script>

更详细的原创:https://www.jb51.net/article/132371.htm

猜你喜欢

转载自blog.csdn.net/weixin_47886687/article/details/115399709