Vue2.0父子组件传值总结

一.父组件向子组件传数据

<!-- 父组件father -->
<!-- 父组件通过message属性把msg的值传给子组件child -->
<template>
  <div>
   <child :message="msg"></child>
  </div>
</template>

<script>
import Child from './child'
export default {
  name: 'father',
  data () {
    return {
      msg: 'this is msg'
    }
  },
  components:{
    Child
  }
}
</script>
<!-- 子组件child -->
<!-- 子组件通过props接收父组件传的值 -->
<template>
  <div>
   {{message}}
  </div>
</template>

<script>
export default {
    props:['message']
   
}
</script>

二.子组件向父组件传数据

<!-- 子组件child -->
<!-- 点击按钮传值 -->
<template>
  <div>
    <button @click="sendMsg">确定</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      newMsg: "msg is Changed"
    };
  },
  methods: {
    sendMsg() {
      this.$emit("msgChanged", this.newMsg);
    }
  }
};
</script>

<!-- 父组件father -->
<template>
  <div>
   <child @msgChanged="showMsg"></child>
  </div>
</template>

<script>
import Child from './child'
export default {
  name: 'father',
  components:{
    Child
  },
  methods:{
    showMsg(data){
      console.log(data)   

    }
  }
}
</script>

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_43225030/article/details/89360247