自定义组件使用v-model指令

文章参考

https://cn.vuejs.org/v2/guide/components.html#自定义组件的-v-model

<input v-model="something">

是以下内容的语法糖(等价于)

<input
  v-bind:value="something"
  v-on:input="something = $event.target.value">

备注:

1、v-model相当于传递了一个值是value的props属性

2、并且监听input事件

3、将组建内部的值赋值给定义好的数据

下面的内容是我写的demo 

自定义的组件

<template>
    <!-- 最外层只能有一个组件,不能出现多个 -->
    <!-- 最外层class命名规则 工程-文件路径-文件名  -->
    <div class="">
        {{newData}}
        <button @click="changeData">改变数据</button>

    </div>
</template>

<script>
    export default {
        props:{
            value: "",
        },
        data: function (){
            return {
                newData:"",
            }
        },
        mounted: function(){
            debugger
            console.log("this.value : " + this.value);
        },
        methods: {
            changeData : function (){
                debugger
                this.newData = new Date().getTime() + "----" + this.value;
                this.$emit("input",this.newData);
            }
        },
        watch: {
            input:function (newValue, oldValue) {
                console.log("watch input" + newValue);
            }
        }
    }
</script>

使用自定义组建

<template>
    <!-- 最外层只能有一个组件,不能出现多个 -->
    <!-- 最外层class命名规则 工程-文件路径-文件名  -->
    <div class="demo-extendPrototype-stringExtend">
        <vmodel-comp
            v-model="userinput"
        ></vmodel-comp>
        {{userinput}}
    </div>
</template>

<script>
    import vmodelComp from "./vmodelComp.vue";
    export default {
        mounted: function(){
        },
        data: function (){
            return {
                userinput:"huangbiao"
            }
        },
        components:{
            vmodelComp
        }
    }
</script>

猜你喜欢

转载自hbiao68.iteye.com/blog/2397489
今日推荐