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>
相关推荐
huangdong_6 小时前
淘宝商品SKU图自动分类技术深度解析:从DOM解析到智能归档
开发语言·javascript·ecmascript
xiaofeichaichai9 小时前
ES 新特性九年速览:从 ES2016 到 ES2024
前端·javascript·es6
放下华子我只抽RuiKe510 小时前
FastAPI 全栈后端(四):认证与授权
开发语言·前端·javascript·python·深度学习·react.js·fastapi
如果超人不会飞10 小时前
WebMCP:当浏览器学会和 AI「说人话」,你的网页就成了智能体的游乐场
javascript
整点可乐10 小时前
cesium实现全景图加载
javascript·cesium
dualven_in_csdn11 小时前
一键起飞调用示例
android·java·javascript
meilindehuzi_a11 小时前
通俗易懂掌握树与二叉树:定义、核心概念与JS实现遍历
javascript·ecmascript
胡志辉12 小时前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·面试
gz-郭小敏12 小时前
优化横向滚动展示大量数据的时候数据晃动问题
前端·javascript·html·css3