zoukankan      html  css  js  c++  java
  • 2种方式实现vue自定义组件v-model

    1. 使用value+input事件

    默认情况下,一个组件上的 v-model 会把 value 用作 prop 且把 input 用作 event

    <!-- parent -->
    <template>
      <div class="parent">
        <p>我是父亲, 对儿子说: {{ sthGiveChild }}</p>
        <button @click="changeChild">xxxx</button>
    
        <child v-model="sthGiveChild"></child>
      </div>
    </template>
    <script>
    import child from './child.vue'
    export default {
      data() {
        return {
          sthGiveChild: '给你100块',
        }
      },
      components: {
        child,
      },
      methods: {
        changeChild() {
          this.changeChild = '给你1000块'
        },
      },
    }
    </script>
    
    <!-- child -->
    <template>
      <div class="child">
        <p>我是儿子,父亲对我说: {{ value }}</p>
        <a href="javascript:;" rel="external nofollow" @click="returnBackFn"
          >回应</a
        >
      </div>
    </template>
    <script>
    export default {
      name: 'Child',
      props: {
        value: String,
      },
      methods: {
        returnBackFn() {
          this.$emit('input', '还你200块')
        },
      },
    }
    </script>
    

    2. 使用model自定义事件和prop

    这种方式和第一种效果一样,但是一些输入类型比如单选框和复选框按钮可能想使用 value prop 来达到不同的目的。使用 model 选项可以回避这些情况产生的冲突。

    <!-- child -->
    <template>
      <div class="child">
        <p>我是儿子,父亲对我说: {{ give }}</p>
        <a href="javascript:;" rel="external nofollow" @click="returnBackFn"
          >回应</a
        >
      </div>
    </template>
    <script>
    export default {
      name: 'Child',
      props: {
        give: String,
      },
      model: {
        prop: 'give',
        event: 'returnBack',
      },
      methods: {
        returnBackFn() {
          this.$emit('returnBack', '还你200块')
        },
      },
    }
    </script>
    
    make a difference
  • 相关阅读:
    NET CORE 数据库迁移
    VUE3.0 解析svg文件
    关于ElementUI的样式不生效
    git命令
    vue 2.x的跨域问题
    Putty 重新启动 linux sqlserver服务
    aspnetcore之session
    Syncfusion 在 core 的架构
    TortoiseSVN创建/合并分支
    正则表达式知识点整理
  • 原文地址:https://www.cnblogs.com/paul-xiao/p/14447515.html
Copyright © 2011-2022 走看看