拆分 v-model

拆分 v-model

import Vue from 'vue'

const component = {
  props: ['valueOfSon'],
  template: `
    <div>
      <input type="text" @input="handleInput" :value=valueOfSon>
    </div>
  `,
  methods: {
    handleInput (e) {
      this.$emit('inputToParent', e.target.value)
    }
  }
}

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

稍微解释下,这里使用了父子组件,初始化的时候,父组件中的valueOfParent通过prop传递到子组件中,然后在子组件中使用@input监测输入事件,一旦有输入事件,就调用handleInput方法,方法中使用$emit触发父组件中inputToParent事件,并且还有一个参数,也就是input框中的值,其中 e 代表event,父组件的@inputToParent收到信号后,调用了后面的方法,也就是给valueOfParent赋值,赋的值为第一个参数,从而实现了v-model的效果。

猜你喜欢

转载自blog.csdn.net/zhuyuchen321/article/details/81941256
今日推荐