vue父组件传值给子组件


一、父传子

方式一

父传子主要通过在父组件v-model绑定数据,在子组件进行用props进行数据的接收

父组件

<template>
    <div id="container">
        <Child :msg="data"></Child>
    </div>
</template>
<script>
import Child from "@/components/Child";
export default {
  data() {
    return {
      data: "父组件的值"
    };
  },
  methods: {
  },
  components: {
    Child
  }
};
</script>

 

子组件

<template>
    <div id="container">
        <h1>{{msg}}</h1>
    </div>
</template>
<script>
export default {
  data() {
    return {};
  },
  props:["msg"]
};
</script>

 

方式二

父组件触发子组件的方法,主要通过$refs来触发,同时传参

父组件

<template>
    <div id="container">
    <h1 @click="getData">点击将触发子组件方法,并把参数传给子组件</h1>
      <child ref="mychild"></child>
    </div>
</template>
<script>
import Child from "@/components/Child";
export default {
  data() {
    return {
        name: '',
        age: ''
    };
  },
  
  components: {
    Child
  }
  
  methods: {
  getData(){
    //触发子组件方法,并传参
        this.$refs.mychild.init("chrchr","120");
  } 
  
  },
  
};
</script>

 

子组件

<template>
    <div id="container">
        <h1>{{name}}</h1>
        <h1>{{age}}</h1>
    </div>
</template>
<script>
export default {

  props:["msg"],
  
  data() {
    return {
        name: '',
        age: ''
    };
  },
  
  mounted:{
    
  },  
  method:{
    //父组件触发子组件的init方法
    init(name,age){
        this.name = name;
        this.age = age;
    }
  }
};
</script>

 

 

 

 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM