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

     

    1.在子组件里面定义,子组件用 $emit() 触发事件,$emit() 第一个参数为 自定义的事件名称 第二个参数为需要传递的数据

    this.$emit('myEvent',value)

    2.在父组件里面通过在组件里设置,父组件用v-on 监听子组件的事件,@myEvent  是子组件中$emit 定义传触发事件名称,getValue是事件源,定义在父组件当中;

    @myEvent="getValue"

    3.在父组件method方法里面定义

    getValue(value){
       console.log('value',value)  //取值
    }

    实例:

    定义根组件

      <!-- 定义根组件 -->
      <div id="app">
       <a-father @father-text="fathers"></a-father>
      </div>

    逻辑代码:

      <script>
        // 定义一个全局的子组件,a-father是new vue的子组件
       Vue.component('a-father',{
         template: `<div>
          // 这里的是子组件a-son组件,@enlarge-text事件是子组件$emit触发的自定义事件名称,handle才是事件源,handle函数定义在父组件的methods里面;子组件只能在父组件模板里面使用,
          <a-son @enlarge-text="handle"></a-son>
          <button @click='$emit("father-text", "父组件")'>父组件</button>
          </div>`,
         data: function() {
           return{
           }
         },
         methods:{
        //handle函数才是事件源,handle函数必须定义在父组件中 handle(a){ console.log(a);  //参数a为子组件传递的参数 } }, components:{
    'a-son':{ // 子组件定义一个按钮,$emit()会触发里面定义的enlarge-text自定义事件,第二个为传递的参数; template:`<div><button @click='$emit("enlarge-text", 5)'>扩大父组件中字体大小</button></div>`, data:function(){ return{ } } } } }) const vm = new Vue({ el:'#app', data: { msg:'vue' }, methods:{ fathers(a){ console.log(a); } } }) </script>
    时间如白驹过隙,忽然而已,且行且珍惜......
  • 相关阅读:
    解决 WordPress 后台加载非常缓慢/打不开问题
    PHP 数组函数 内部指针
    date picker with jquery
    PHP is_file() 函数
    redis 应用场景-转载
    mvc 伪静态 *html IIS 部署 404 错误
    记录7: office 2016 Mac不能使用的解决过程
    send_keys results in Expected 【object Undefined】undefined to be a string解决方法:更新selenium+geckodriver+firefox
    记录1-更换mac pro内存,硬盘及恢复系统
    记录2-在mac上安装ubuntu 16.04 LTS
  • 原文地址:https://www.cnblogs.com/UnfetteredMan/p/13964340.html
Copyright © 2011-2022 走看看