vue v-model 语法糖

1. v-model、@input 实现双向绑定数据

<template>
  <div id="app">
    <div>
      <label>value、@input实现双向绑定数据:</label>
      <input :value="v1" @input="event1">
      <div>输入框中的值:{{ v1 }}</div>
    </div>
    <div>
      <label>v-model实现双向绑定数据:</label>
      <input v-model="v2">
      <div>输入框中的值:{{ v2 }}</div>
    </div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      v1: '',
      v2: '',
    }
  },
  methods: {
    event1(e) {
      this.v1 = e.target.value
    },
  },
}
</script>

2. v-model 在组件中使用(简化代码:等价于@input方式)

  1. 在父组件中、使用 v-model 在子组件上绑定数据
<template>
  <div id="app">
    <div>
      <vmodel v-model="v1"></vmodel>
      <div>{{ v1 }}</div>
    </div>
  </div>
</template>

<script>
import vmodel from './components/vmodel.vue'
export default {
  name: 'App',
  components: {
    vmodel,
  },
  data() {
    return {
      v1: 'v1',
    }
  },
  methods: {
    input(v) {
      this.v1 = v
    },
  },
}
</script>
  1. 在子组件中,可当作父组件已绑定 :value 和 @input
<template>
  <div>
    <div @click="changeMe()">
      点我
    </div>
    <div>{{ value }}</div>
  </div>
</template>

<script>
export default {
  name: 'vmodel',
  props: {
    value: {
      type: [String],
      default: '',
    },
  },
  methods: {
    changeMe() {
      this.$emit('input', '改变了哦')
    },
  },
}
</script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容