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>
相关推荐
DanB2414 分钟前
html复习
javascript·microsoft·html
呼啦啦呼啦啦啦啦啦啦6 小时前
利用pdfjs实现的pdf预览简单demo(包含翻页功能)
android·javascript·pdf
前端 贾公子9 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
拾光拾趣录9 小时前
链表合并:双指针与递归
前端·javascript·算法
拼图2099 小时前
element-plus——图标推荐
javascript·vue.js·elementui
期待のcode9 小时前
图片上传实现
java·前端·javascript·数据库·servlet·交互
koooo~10 小时前
JavaScript中的Window对象
开发语言·javascript·ecmascript
安心不心安11 小时前
React hooks——useReducer
前端·javascript·react.js
像风一样自由202011 小时前
原生前端JavaScript/CSS与现代框架(Vue、React)的联系与区别(详细版)
前端·javascript·css
啃火龙果的兔子11 小时前
react19+nextjs+antd切换主题颜色
前端·javascript·react.js