美文网首页
vue 父子组件交互

vue 父子组件交互

作者: 咕嘟咕嘟li | 来源:发表于2018-01-21 22:43 被阅读141次

    要点:
    1.父组件定义值传递过去
    2.子组件prpos接收使用,watch监测props内值的变化
    3.修改后使用$emit反馈给父组件

    举个栗子🌰(父组件控制子组件的显示/隐藏):

    // 定义父组件
    <template>
      <div class="stu-parent">
        <div class="stu-parent-wrap">this is parent</div>
        <button @click="clickButton()">click parent</button>
        <div class="stu-child-wrap">
          <stu-child-demo :showChild="childBol" @myClick="hideChild"></stu-child-demo>
        </div>
      </div>
    </template>
    <script>
      import StuChildDemo from '@/components/demo/StuChildDemo'
      export default {
        data () {
          return {
            // 定义该变量传递给子组件
            childBol: false
          }
        },
        components: {StuChildDemo},
        methods: {
          clickButton () {
            this.childBol = true;
          },
    
          // 接收子组件反馈过来的数据,并使用
          hideChild (val) {
            this.childBol = val;
          }
        }
      };
    </script>
    
    
    // 定义子组件
    <template>
      <div class="stu-child" style="margin-top:100px;" v-if="visible">
        I'm the child!
        <button @click="myClick()">click me</button>
      </div>
    </template>
    <script>
      export default {
        props: {
          // 接受父组件传入的值
          showChild: false
        },
        data () {
          return {
            visible: this.showChild
          }
        },
        methods: {
          myClick () {
            this.visible = false;
    
            // 子组件传递值给父组件
            this.$emit('myClick', this.visible);
          }
        },
        watch: {
          // 监测父组件传入的值
          showChild (val) {
            this.visible = val;
          }
        }
      };
    </script>
    
    

    相关文章

      网友评论

          本文标题:vue 父子组件交互

          本文链接:https://www.haomeiwen.com/subject/srmroxtx.html