Vue-绑定自定义事件

1.定义

​ 1.一种组件间通信的方式,适用于: 子组件===>父组件

​ 2.使用场景:A是父组件,B是子组件,B想给A传递数据,那么就给在A中给B绑定自定义事件(事件的回调在A中)

​ 3.绑定自定义事件:

1.方式一

​ 在父组件中:

<School @getSchoolName="getSchoolName" />

或者

<School v-on:getSchoolName="getSchoolName" />

2.方式二 在父组件中定义ref

<School  ref="schoolName"/>  
  mounted(){
 						      this.$refs.XXXX.$on('getSchoolName',this.getSchoolName)   	
  },
  methods:{
    getSchoolName(name){ 
      this.schoolName = name
    }
  }

3.若想让自定义事件只能触发一次,可以使用once修饰符或者$once方法

​ 4.触发自定义事件:在子组件中定义函数

this.$emit('getSchoolName',this.schoolName)

​ 5.解绑自定义事件

this.$off('getSchoolName')

​ 6.组件上绑定原生DOM事件,需要使用native修饰符

​ 7.通过ref绑定自定义事件,回调要么配置在methods中,要么使用箭头函数,否则this的指向会出问题

​ 8.使用ref绑定自定义事件相比于@和v-on的好处:ref可以更加灵活,比如添加setInterval函数,可以给事件绑定设置延迟

2.示例

需求:点击按钮,将子组件scholl和student的schoolName和studentName传给父组件App

在school组件中:

<div class="school">
    <span>{{schoolName}}</span>
    <button @click="sendShoolName">将学校名传给父组件</button>
  </div>
export default {
  data(){
    return{
      schoolName:'北京大学'
    }
  },
  methods:{
     sendShoolName(){
            this.$emit('getSchoolName',this.schoolName)
        }
  }
}

在student组件中:

  <div class="student">
      <span>{{studentName}}</span>
      <button @click="sendStudentName">将学生名传给父组件</button>
    </div>
export default {
    data(){
        return{
            studentName:'张三'
        }
    },
    methods:{
        sendStudentName(){
            this.$emit('getStudentName',this.studentName)
        }
    }
}

在父组件App中

 <div id="app">
    <!-- 使用@或者v-on自定义事件 -->
    <!-- <School @getSchoolName="getSchoolName" />   -->
    <!-- 使用ref自定义事件 -->
    <School  ref="schoolName"/>  
    <!-- 在组件中使用原生的click事件需要加上native修饰符 -->
    <Student @getStudentName="getStudentName" @click.native="show"/>  
    <span>{{studentName}}</span>
    <span>{{schoolName}}</span>
  </div>
import School from './components/school.vue'
import Student from './components/student.vue'
export default ({
  name:'App',
  components:{School,Student},
  data(){
    return{
      studentName:'',
      schoolName:''
    }
  },
  mounted(){
    setInterval(()=>{
      this.$refs.schoolName.$on('getSchoolName',this.getSchoolName)
    },3000)
    
  },
  methods:{
    show(){
      alert('哈哈哈')
    },
    getSchoolName(name){ 
      console.log('###',name);
      this.schoolName = name
    },
     getStudentName(name){
      console.log('###',name);
      this.studentName = name
    }
  }
})
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值