Vue父子之间的传值

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
  <title>Document</title>
  <style>
    * {
      margin: 0;
      padding: 0;
    }

    html,
    body,
    #app1 {
      width: 100%;
      height: 100%;
    }

    .wrapper {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100%;
      height: 100%;
      background-color: rgba(0, 0, 0, 0.3);
      position: fixed;
      top: 0;
      left: 0;
    }

    .content {
      width: 220px;
      height: 160px;
      background-color: #fff;
    }

    .title {
      height: 40px;
      line-height: 40px;
      text-align: center;
    }

    .msg {
      display: flex;
      align-items: center;
      justify-content: center;
      box-sizing: border-box;
      padding: 5px 10px;
      border-top: 1px solid #eee;
      border-bottom: 1px solid #eee;
      height: 80px;
      text-align: center;
      color: gray;
      font-size: 14px;
    }

    .bottom {
      display: flex;
      height: 40px;
      line-height: 40px;
      text-align: center;
    }

    .bottom div {
      flex: 1;
      color: green;
    }

    .bottom div:nth-of-type(1) {
      border-right: 1px solid #eee;
      color: red;
    }
  </style>

</head>

<body>
  <div id="app1">
    <p>点击结果:{{clickResult}}</p>
    <!-- 插入父组件 -->
    <!--2. 创建自定义方法给子组件 -->
    <!-- 2.自定义属性接收父组件的值 -->
    <child :obj="textObj" @fn="changClickResult"></child>
  </div>
  </div>
</body>

<!-- 创建模板 -->
<template id="wrap">
  <div class="wrapper" v-show="isShow">
    <div class="content">
      <!-- 3.接收的值渲染页面 -->
      <p class="title">{{obj.title}}</p>
      <div class="msg">{{obj.msg}}</div>
      <div class="bottom">
        <!--3. 绑定事件触发自定义方法给父组件传值 -->
        <div @click="hdClick(obj.cancelTxt)">{{obj.cancelTxt}}</div>
        <div @click="hdClick(obj.submitTxt)">{{obj.submitTxt}}</div>
      </div>
    </div>
</template>


<script>

  //创建子组件
  let child = {
    template: '#wrap',
    //1. 自定义属性
    props: ['obj'],
    data() {
      return {
        //弹窗状态
        isShow: true
      }
    },
    methods: {
      hdClick(val) {
        //Vue内置API触发
        this.$emit('fn', val)
        //关闭弹窗
        this.isShow = false;

      }
    }
  }

  // 现有以上布局,把wrapper抽取成子组件,通过传值的方式往内部传递数据
  new Vue({
    el: '#app1',
    data: {
      textObj: {
        title: 'bug提示',
        msg: '亲,你还有53633个bug,是否要处理?',
        cancelTxt: '忽略,下班',
        submitTxt: '加班处理'
      },
      clickResult: ""
    },
    //注册组件
    components: {
      child
    },
    methods: {
      //1.父组件提供子组件传值的方法
      changClickResult(val) {
        this.clickResult = val
      }
    }
  })
</script>

</html>

  

posted @ 2022-02-26 19:06  Gawaine  阅读(49)  评论(0)    收藏  举报