vue2 自定义 v-model (model选项的使用)

效果预览

model 选项的语法

  • 每个组件上只能有一个 v-model。
  • v-model 默认会占用名为 value 的 prop 和名为 input 的事件,即 model 选项的默认值为
bash 复制代码
  model: {
    prop: "value",
    event: "input",
  },
  • 通过修改 model 选项,即可自定义v-model 的 prop 和 event

演示代码

父组件 father.vue

html 复制代码
<template>
  <div style="margin: 30px">
    <p style="margin: 30px">{{ msg }}</p>
    <Child v-model="msg" />
  </div>
</template>

<script>
import Child from "./child.vue";
export default {
  components: {
    Child,
  },
  data() {
    return {
      msg: "你好",
    };
  },
};
</script>

子组件 child.vue

html 复制代码
<template>
  <div>
    <input type="text" @input="chang_parentMsg" :value="parentMsg" />
  </div>
</template>

<script>
export default {
  model: {
    prop: "parentMsg",
    event: "chang_parentMsg",
  },
  props: {
    parentMsg: String,
  },
  methods: {
    chang_parentMsg(e) {
      this.$emit("chang_parentMsg", e.target.value);
    },
  },
};
</script>
相关推荐
gnip1 小时前
企业级配置式表单组件封装
前端·javascript·vue.js
掘金安东尼4 小时前
抛弃自定义模态框:原生Dialog的实力
前端·javascript·github
hj5914_前端新手7 小时前
javascript基础- 函数中 this 指向、call、apply、bind
前端·javascript
Hilaku8 小时前
都2025年了,我们还有必要为了兼容性,去写那么多polyfill吗?
前端·javascript·css
LuckySusu8 小时前
【js篇】JavaScript 原型修改 vs 重写:深入理解 constructor的指向问题
前端·javascript
LuckySusu8 小时前
【js篇】如何准确获取对象自身的属性?hasOwnProperty深度解析
前端·javascript
LuckySusu8 小时前
【js篇】深入理解 JavaScript 作用域与作用域链
前端·javascript
LuckySusu8 小时前
【js篇】call() 与 apply()深度对比
前端·javascript
LuckySusu8 小时前
【js篇】addEventListener()方法的参数和使用
前端·javascript
LuckySusu8 小时前
【js篇】深入理解 JavaScript 原型与原型链
前端·javascript