美文网首页测试员的那点事
零基础学vue-组件的双向绑定v-model

零基础学vue-组件的双向绑定v-model

作者: 望月成三人 | 来源:发表于2020-10-31 17:35 被阅读0次
<html>
    <head>
        <meta charset="utf-8">
        <title>组件的双向绑定</title>
        <script type="application/x-javascript" src="js/vue.js"></script>
        
    </head>
    <body>
        <div id="app">
            <input-com :username="username" @child-input="changeEvent"></input-com>
            <input-com :username="username" @child-input="username=$event"></input-com>
            <input-com1 v-model="username"></input-com1>
            <h3>{{username}}</h3>
        </div>
        <script type="text/javascript">
            Vue.component("input-com", {
                props:["username"],
                //$event.target.value 表示获取当前输入框绑定的value的值
                template:`
                    <input type="text" @input="$emit('child-input',$event.target.value)" :value="username" />
                `
            })
            
            Vue.component("input-com1", {
                props:["username"],
                template:`
                    <input type="text" @input="$emit('input',$event.target.value)" :value="username" />
                `
            })
            
            var app = new Vue({
                el: "#app",
                data: {
                    username: ""
                },
                methods:{
                    changeEvent:function(data){
                        this.username = data
                    }
                }
            })
        </script>
    </body>
</html>
  • 子组件值发生变化,父节点的值也会发生变化

相关文章

网友评论

    本文标题:零基础学vue-组件的双向绑定v-model

    本文链接:https://www.haomeiwen.com/subject/cmosvktx.html