vue自定义组件上的v-model--2020-01-10

1,子组件通过v-model属性获取父组件的数据

子组件:

 <template>

  <div>

      {{value}}

  </div>

</template>

<script>

export default {

    props : {

        value : [String, Number]

    }

}

</script>


父组件:

<template>

  <div>

     <test v-model="active"></test>

  </div>

</template>

<script>

import test from './test';

export default {

  data () {

    return {

      active:2

    }

  }

2,子组件通过v-model获取父组件的数据,子组件改变父组件的数据

子组件:

<template>

    <div>

        <div>{{msg}}</div>

        <div>

            <ul>

                <li v-for="(item,index) in option" :key="index"  @click="Change(item)">{{item}}</li>

            </ul>

        </div>

    </div>

</template>

<script>

export default {

    props:['option','msg'],

    model:{

        prop:'msg',

        event:'cc'

    },

    methods:{

        Change(data){

            this.$emit('cc',"我变了");

        }

    },

    mounted(){

        console.log(this.msg);

    }

}

</script>

父组件使用:

 <z-select v-model="val" :option="option"></z-select>

  data () {

    return {

      option:["aaa","bbb","ccc"],

      val:"请输入"

    }

  },

3,[endif]父组件通过v-model模仿 input标签的v-model属性

  <template>

  <div>

      <input type="text" v-model="newValue" @input="change">

  </div>

</template>

export default {

    props: ['value'],

    data(){

        return {

            newValue:this.value

        }

    },

    methods:{

        change(){

            this.$emit("input", this.newValue);

        }

    },

}

备注;

父组件的v-model值接收子组件中props中的value值

子组件初始化newValue的值为父组件v-model中接收的值

之后子组件不断的改变并发射input事件,送出newValue值


子组件的另一种写法:

<template>

  <div>

      <input type="text" v-model="newValue" @input="change">

  </div>

</template>

<script>

export default {

    props: ['value'],

    data(){

        return {

            newValue:this.value

        }

    },

    methods:{

        change(){

            this.$emit("input", this.newValue);

        }

    },

    computed:{

        newValue:{

            get(){

                return this.value;

            },

            set(value){

                this.$emit("input",value);

            }

        }

    }

}

</script>

父组件:

<input-ele v-model="active" @input="getValue"></input-ele>

   getValue(event){

     console.log(event,"接收文本框输入的值");

    }

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Vue组件之间通信的七种方式 使用Vue也有很长一段时间,但是一直以来都没对其组件之间的通信做一个总结,这次就借此...
    豆豆_4edc阅读 3,749评论 0 2
  • Vue 实例 属性和方法 每个 Vue 实例都会代理其 data 对象里所有的属性:var data = { a:...
    云之外阅读 6,646评论 0 6
  • 组件的基础 # 组件基础 ## 什么是组件 >对我们的页面中的共用的元素,进行拆分,单独做成一个模块,方便后续的使...
    考拉_2044阅读 2,571评论 0 0
  • 问题 点击跳转到原文 在vue2中对表单控件有着良好的双向数据绑定机制,但是对于要特定实现某些功能的输入时,我们就...
    九千_阅读 5,231评论 0 1
  • vue是一套用于构建用户界面的渐进式框架,采用自底向上的增量设计。可以先用自己想要的部分,然后慢慢加第三方库。而不...
    Da_xiong阅读 8,159评论 0 3