zoukankan      html  css  js  c++  java
  • vue子组件向父组件传值

    vue2.0中通过$emit事件在子组件中自定义事件,通过操作子组件中的事件,向父组件传递参数;

    首先写一个叫做parentComp.vue的父组件:

    <template>
      <div>
        <childComp01 :fromParentToChild="fromParentToChild" :isShow="show" @showParentComp="eventFromChild"></childComp01>
        <childComp02 @eventFromChild02="eventFromChild02" :fromParentToChild="fromParentToChild" :isShow="!show"></childComp02>
      </div>
    
    </template>
    <script>
      import childComp01 from './childComp.vue'
      import childComp02 from './childComp02.vue'
      export default{
        data(){
          return{
            show:false,//是否展示子组件内容
            fromParentToChild:""
          }
        },
        components:{childComp01,childComp02},
        methods:{
          showChild(){
            this.show = true
          },
          eventFromChild(dataIf){
            console.log(dataIf.show)
            this.show=dataIf.show
            this.fromParentToChild = dataIf.mes
          },
          eventFromChild02(dataIf){
            console.log(dataIf.show)
            this.show=dataIf.show
            this.fromParentToChild = dataIf.mes
          }
        }
      }
    </script>
    

      

    然后定义子组件childComp01和childComp02

    <template>
      <div v-if="isShow">
        <div>子组件内容01:</div>
        {{fromParentToChild}}
        <div>
          <button @click="showParentComp">点击显示子组件02内容</button>
        </div>
      </div>
    </template>
    <script>
      export default{
        props:['fromParentToChild','isShow'],
        data(){
          console.log(this.fromParentToChild)
          return{
            dataIf:{
              mes:"来自子组件01的内容",
              show:false
            }
          }
        },
        methods:{
          showParentComp(){
            this.$emit("showParentComp",this.dataIf)
          }
        }
      }
    </script>
    

      

    childComp02.vue

    <template>
      <div class="childComp-02" v-if="isShow">
        {{fromParentToChild}}
        <div><button @click="toParentComp">这是子组件02</button></div>
      </div>
    </template>
    <script>
      export default{
        props:['isShow','fromParentToChild'],
        data(){
          return{
            dataIf:{
              show:true,
              mes:"从子组件02传过来的信息"
            }
          }
        },
        methods:{
          toParentComp(){
            this.$emit("eventFromChild02",this.dataIf)
          }
        }
      }
    </script>
    

      

  • 相关阅读:
    Javascript自动打开匹配的超链接
    Javascript 广告浮动效果在浏览器中间N秒后移动到右下角
    吾爱破解论坛有漏洞!!所有资源都曝光了...开心吧
    C# Ajax 技术
    花花公子写代码
    C++ Strings(字符串)
    C++语言的I/o使用方法详解
    标准c内存函数的使用方法
    [原]Python 简单文件处理
    [原]Python 简单异常处理
  • 原文地址:https://www.cnblogs.com/zhangxiaoshu/p/6710361.html
Copyright © 2011-2022 走看看