Vue子父传值

1、子组件中某个元素绑定常规事件

2、子组件事件函数中写上this.$emit("自定义事件名称',传递的值)

3、在父组件中通过给子组件的调用上通过v-on指令绑定自定义事件,自定义时间名称与子组件中的自定义时间名称一致

4、在父组件中声明自定义函数,通过参数e来获取得到子组件传递过来的值

具体代码如下

<!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">
  <title>Document</title>
  <!-- 导入 vue 文件 -->
  <script src="js/vue-2.4.0.js"></script>
</head>

<body>
  <!-- 
      子组件传值父组件的过程:
          1、子组件中某一个元素绑定常规事件
          2、子组件事件函数中写上 this.$emit("自定义事件名称",传递的值)
          3、在父组件中通过v-on:指令(注意不能用@)绑定自定义事件,自定义事件名称与子组件中的"自定义事件名称一致"
          4、在父组件methods中声明自定义函数,通过参数e获取得到子组件传递的数值
   -->
  <!-- 被 vm 实例所控制的区域 -->
  <div id="app">
    <father v-on:send-root="getFatherData"></father>
  </div>
  <!-- // 父组件 -->
  <template id="father">
    <div>
      <h1>我是父组件标题</h1>
      <!-- 3、 -->
      <son v-on:send-father="getChildData" v-on:sendparent="getSonData"></son>
      <h5>我是父组件内容</h5>
      <h6>{{name}}</h6>
      <button @click="event3">我是father按钮</button>
    </div>
  </template>
  <!-- // 子组件 -->
  <template id="son">
    <div>
      <h1>我是子组件标题</h1>
      <!-- 1、 -->
      <button @mouseover="event1">蛋妞1</button>
      <button @dblclick="event2">按钮2</button>
    </div>
  </template>
  <script>
    // 子组件
    const son = {
      template: "#son",
      data () {
        return {
          arr: ["喜洋洋", "美羊羊"],
          num: 100
        }
      },
      methods: {
        event1 () {
          console.log(1111);
          // 2、
          this.$emit("send-father", { name: "给爸爸的值" })
        },
        event2 () {
          this.$emit("sendparent", this.arr, this.num)
        }
      }
    }
    // 父组件
    const father = {
      template: "#father",
      data () {
        return {
          name: ""
        }
      },
      methods: {
        // 4、
        getChildData (e) {
          console.log(e);
          console.log(e.name);
          this.name = e.name;
        },
        // 用两个参数接受
        getSonData (a, b) {
          console.log(a);
          console.log(b);
        },
        event3 () {
          this.$emit("send-root", 325, this.name)
        }
      },
      components: {
        son
      }
    }

    // 创建 vm 实例对象
    const vm = new Vue({
      // 指定控制的区域
      el: '#app',
      data: {

      },
      methods: {
        getFatherData (m, n) {
          console.log(m, n);
        }
      },
      components: {
        father,
      }
    });
  </script>
</body>

</html>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值