vue父子组件间传值

父组件给子组件传值

父组件:

<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>

 

 

 

子组件给父组件传值:通过  this.$emit 来传值

<template>
    <div class="app">
       <input @click="sendMsg" type="button" value="给父组件传递值">
    </div>
</template>
<script>
export default {
 
    data () {
        return {
            //将msg传递给父组件
            msg: "我是子组件的msg",
        }
    },
     methods:{
         sendMsg(){
             //func: 是父组件指定的传数据绑定的函数,this.msg:子组件给父组件传递的数据
             this.$emit('func',this.msg)
         }
     }
}
</script>

父组件接收:

<template>
    <div class="app">
        <child @func="getMsgFormSon"></child>
    </div>
</template>
<script>
import child from './child.vue'
export default {
    data () {
        return {
            msgFormSon: "this is msg"
        }
    },
    components:{
        child,
    },
    methods:{
            getMsgFormSon(data){
                this.msgFormSon = data
                console.log(this.msgFormSon)
            }
    }
}
</script>

 

 

这两种传值也可以通过 vuex 来实现

 

posted @ 2020-05-07 15:43  我是木木呀  阅读(254)  评论(0编辑  收藏  举报