vue中父组件与子组件之间数据传递

父组件向子组件传值

  1. 组件实例定义方式,注意:一定要使用props属性来定义父组件传递过来的数据
  2. 使用v-bind或简化指令,将数据传递到子组件中
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
    <title>Document</title>
</head>
<body>
    <div id="app">
      <!-- 使用v-bind或简化指令,将数据传递到子组件中 -->
      <son :father="msg" :father2="msg2"></son>
    </div>
    <script>
      var vm = new Vue({
        el: '#app',
        data: {
          msg:'父组件数据',
          msg2:'父组件2'
        },
        methods: {},
        components:{
          son:{
            template:'<h1>我是子组件:使用---{{father}} ---- {{father2}}</h1>',
            props:['father','father2']
          }
        }
      });
    </script>
</body>
</html>

展示效果:
在这里插入图片描述


子组件向父组件传值

  1. 原理:父组件将方法的引用,传递到子组件内部,子组件在内部调用父组件传递过来的方法,同时把要发送给父组件的数据,在调用方法的时候当作参数传递进去;
  2. 父组件将方法的引用传递给子组件,其中,getMsg是父组件中methods中定义的方法名称,func是子组件调用传递过来方法时候的方法名称
  3. 子组件内部通过this.$emit('方法名', 要传递的数据)方式,来调用父组件中的方法,同时把数据传递给父组件使用
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <link href="https://cdn.jsdelivr.net/npm/animate.css@3.5.1" rel="stylesheet" type="text/css">
    <title>Document</title>
</head>
<body>
    <div id="app">
      <!-- 使用v-bind或简化指令,将数据传递到子组件中 -->
      <son @father="getMsg"></son>
    </div>

    <!-- 组件模板定义 -->
    <script type="x-template" id="son">
      <div>
        <input type="button" value="向父组件传值" @click="sendMsg" />
      </div>
    </script>

    <script>

      // 子组件的定义方式
      Vue.component('son', {
        template: '#son', // 组件模板Id
        methods: {
          sendMsg() { // 按钮的点击事件
            this.$emit('father', 'OK'); // 调用父组件传递过来的方法,同时把数据传递出去
          }
        }
      });
      var vm = new Vue({
        el: '#app',
        data: {
          
        },
        methods: {
          getMsg(val){ // 子组件中,通过 this.$emit() 实际调用的方法,在此进行定义
              alert(val)
          }
        }
      });
    </script>
</body>
</html>

效果展示:点击按钮,弹窗获取子组件的数据
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值