zoukankan      html  css  js  c++  java
  • vue双向数据绑定

    vue双向数据绑定v-model的实现原理

    定义组件com-one如下

    <template>
    <div>
    <input type="text" @input = 'handlinput' :value="value">
    </div>
    </template>

    <script>
    export default {
    props :['value'],
    name: "com-one",
    methods : {
    handlinput(e){
    this.$emit('input',e.target.value)
    console.log(e.target.value)
    }
    }
    }
    script>
    子组件自定义事件
    input自定义方法handlinput,在方法中$emit事件input,同时从父组件中获取变量value绑定到组件input中,

    父组件监听子组件的发射的事件input,在data中定义value给子组件传递过去因为子组件通过$emit发射的事件传递一个参数因此监听的等于argments[0],这样当父组件中输入值子组件也会同时变化值
    这可以在vue-tool中看到,因此可以在父组件中可以用v-model来使用使用如下v-model="value"代替:value = value @input="value = arguments[0]"这样实现了父组件监听子组件的输入情况
    在父组件helloword中引入
      import comone from './com-one'
    <comone :value = value @input="value = arguments[0]"></comone>
    <comone v-model="value"></comone>
     
    export default {
    components : {
    comone
    },
    data () {
    return {
    value:'123',
    }
    }
    }
    </script>




    也可以自定义model
    还和上面一样这里定义了model对象
    model :{prop :'value1',event :'change'},让从父组件中由原来的value变成定义的vaule1,将原来定义的事件input更改为change事件这样也可以实现刚才的mocdel
     
    <template>
    <div>
    <input type="text" @input = 'handlinput' :value="value1">
    </div>
    </template>

    <script>
    export default {
    model :{
    prop :'value1',
    event :'change',
    },
    props :['value1'],
    name: "com-one",
    methods : {
    handlinput(e){
    this.$emit('change',e.target.value)
    console.log(e.target.value)
    }
    }
    }
    </script>
     
     


  • 相关阅读:
    使用Speex中的AEC模块,提高声音质量(转)
    音频编解码speex库的使用方法
    VC 多线程编程(转)
    并口、串口、COM口区别
    用GDB调试程序
    [转]PCM文件格式
    PreTranslateMessage作用和使用方法
    音频编解码标准
    VS2010 运行速度加快方法(转)
    ON_COMMAND ON_MESSAGE ON_NOTIFY区别与联系
  • 原文地址:https://www.cnblogs.com/zhx119/p/10145817.html
Copyright © 2011-2022 走看看