美文网首页
父子组件传值

父子组件传值

作者: newway_001 | 来源:发表于2019-07-10 19:48 被阅读0次
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="UTF-8">
         <script src="https://cdn.jsdelivr.net/npm/vue@2.6.10/dist/vue.js"></script>
        </head>
    
    <body>
    <div id='app'>
    <table>
                    <tr>
                        <th colspan="3">父组件数据</th>
                    </tr>
                    <tr>
                        <td>名字</td>
                        <td>{{name}}</td>
                        <td><input type="text" v-model="name" /></td>
                    </tr>
                    <tr>
                        <td>年龄</td>
                        <td>{{age}}</td>
                        <td><input type="text" v-model="age" /></td>
                    </tr>
    
                </table>
                <my-component :my-name="name" :my-age="age"
     @change-name="setName" @change-age="setAge">
    </my-component>
    
    </div>
     <template id="myComponent">
                <table>
                    <tr>
                        <th colspan="3">子组件数据</th>
                    </tr>
                    <tr>
                        <td>名字</td>
                        <td>{{myName}}</td>
                        <td><input type="text" v-model="myName" /></td>
                    </tr>
                    <tr>
                        <td>年龄</td>
                        <td>{{myAge}}</td>
                        <td><input type="text" v-model="myAge" /></td>
                    </tr>
                </table>
            </template>
    
    
    
    <script>
    
    var vm=new Vue({
    
    el:'#app',
    data:{name:'小明',
          age:'24'
      },
    components: {
                        'my-component': {
                            template: "#myComponent",
                            props: ["myName", "myAge"],
                            watch: { //监听外部对props属性myName,myAge的变更
                                myName: function(val) {
                                    this.$emit("change-name", val) //组件内对myName变更后向外部发送事件通知
                                },
                                myAge: function(val) {
                                    this.$emit("change-age", val) //组件内对myAge变更后向外部发送事件通知
                                }
                            }
                        }
                    },
                    methods: {
                        setName: function(val) {
                            this.name = val; 
    //外层调用组件方法注册变更方法,
    //将组件内的数据变更,同步到组件外的数据状态中
                        },
                        setAge: function(val) {
                            this.age = val;
                        }
                    }
    
    })
    </script>
    </body>
         
    
    </html>
    
    image.png

    相关文章

      网友评论

          本文标题:父子组件传值

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