欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

Vue组件内部实现一个双向数据绑定的代码示例

程序员文章站 2022-03-08 21:32:34
...
本篇文章给大家带来的内容是关于Vue组件内部实现一个双向数据绑定的代码示例,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
思路:父组件通过props传值给子组件,子组件通过 $emit 来通知父组件修改相应的props值,具体实现如下:
import Vue from 'vue'
const component = {
    props: ['value'],
      template: `
        <div>
            <input type="text" @input="handleInput" :value="value">
        </div>
    `,
      data () {
          return{}
      },
      methods: {
        handleInput (e) {
            this.$emit('input', e.target.value)
        }
    }
}

new Vue({
    components: {
        CompOne: component
      },
      el: '#root',
      template: `
        <div>
          <comp-one :value1="value" @input="value = arguments[0]"></comp-one>
        </div>
      `,
  data () {
    return{
        value: '123'
    }
  }
})

【相关推荐:JavaScript视频教程

以上就是Vue组件内部实现一个双向数据绑定的代码示例的详细内容,更多请关注其它相关文章!

相关标签: javascript