Vue&React事件處理

聲明:


事件處理的方式

當(dāng)子組件不足以處理某個事件時,事件處理有如下兩種方式:

  • 將事件拋給父組件,讓其處理
    這是Vue的標(biāo)準(zhǔn)處理方式
  • 調(diào)用父組件給的處理器進行處理
    這是React的標(biāo)準(zhǔn)處理方式。Vue也可以實現(xiàn)這種處理方式,但是那樣就丟掉了眾多與此相關(guān)的常用指令

拋出式處理方式(Vue示例)
  • MtkInput.vue(子組件)
<template>
    <input type="text" v-on:input="$emit('input',$event.target.value)"/>
</template>

<script>
class MtkInput {
    constructor(){}
}

export default new MtkInput;
</script>
  • MtkInputText.vue(父組件)
<template>
    <div>
        <p>input:{{inputContent}}</p>
        <mtk-input  v-on:input="handleInput"/>
    </div>
</template>

<script>
import MtkInput from './MtkInput.vue'

class MtkInputText {
    constructor(){
        this.data = this.dataInit
        this.components = {
            'mtk-input' : MtkInput
        }
        this.methods = {
            handleInput : this.handleInput
        }
    }

    handleInput(inputContent){ 
        this.inputContent = inputContent
    }

    dataInit(){
        return {
            inputContent : ''
        }
    }
}

export default new MtkInputText;
</script>

這里子組件MtkInput無法處理input事件,然后向父組件拋出一個input事件,并附上輸入的值,父組件MtkInputText監(jiān)聽這個事件然后調(diào)用處理器進行處理
Vue還有更加方便的v-model指令,詳情可看在組件上使用v-model


處理器式處理方式(React示例)
  • MtkInput.js(子組件)
import React from 'react'

class MtkInput extends React.Component {
    constructor(props){
        super(props)
        this.onInput = this.onInput.bind(this)
    }

    onInput(e){
        this.props.onInput(e.target.value)
    }

    render() {
        return (
            <input type="text" onInput={this.onInput}></input>
        )
    }
}

export default MtkInput;
  • MtkInputText.js(父組件)
import React from 'react'
import MtkInput from './MtkInput'

class MtkInputText extends React.Component {
    constructor(props){
        super(props)
        this.state = {inputContent : ''}
        this.onInputHandle = this.onInputHandle.bind(this)
    }

    onInputHandle(inputContent){
        this.setState(()=>{return {inputContent : inputContent};})
    }

    render(){
        return (
            <div>
                <p>input:{this.state.inputContent}</p>
                <MtkInput onInput={this.onInputHandle}/>
            </div>
        )
    }
}

export default MtkInputText;

這里子組件MtkInput無法處理input事件,但是父組件傳入了一個處理器,然后子組件就調(diào)用這個處理器來處理事件


參考文檔:

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容