码迷,mamicode.com
首页 > 其他好文 > 详细

vue父组件传值给子组件

时间:2019-12-04 23:43:47      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:from   round   cli   pre   eth   参数   methods   mod   span   

一、父传子

方式一

父传子主要通过在父组件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>

 

 

 

 

 

vue父组件传值给子组件

标签:from   round   cli   pre   eth   参数   methods   mod   span   

原文地址:https://www.cnblogs.com/caohanren/p/11981066.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!