Vue父子组件之间的传值

1.vue是如何进行父子组件之间的传值的

   a.父子组件之间通过props

   b.子父组件之间通过$emit

2.简单demo描述

   父组件包含一个点击按钮,用于改变子组件的显示与隐藏;

   子组件只有一张图片,以及通过点击图片改变父组件的button的值;

3.实现

   父组件

   

<template>
  <div id="app">
    <Child :showtab="showtable"  @ParentChange="ccc"/> 
    <button @click="changetable">{{buttonval}}</button>
  </div>
</template>

<script>
import Child from './components/Child'

export default {
  name: 'App',
  components: {
      Child
  },
  data(){
    return{
      showtable:true,
      buttonval:"点击改变"
    }
  },
  methods:{
    changetable(){
      this.showtable = !this.showtable;
    },
    ccc(data){
      this.buttonval = data;
    }
  }
}
</script>    

   子组件

扫描二维码关注公众号,回复: 3672445 查看本文章
<template>
    <div id="child" v-show="showtab">
        <div class="box">
            <img src="../../assets/settings.png" 
 @click="changeparent">
        </div>
  </div>
</template>

<script>
    export default {
        name: "Child",
        props:{
          showtab:{      //父组件传过来的值
            type:Boolean
          }
        },
        methods:{
          changeparent(){
            this.$emit("ParentChange","change");   //向父组件进行传值
          }
        }
    }
</script>

猜你喜欢

转载自www.cnblogs.com/Adver/p/9829316.html