• vue2 父子组件间通信


    父组件往子组件传值 props 传text

    father.vue

    <template>
        <div class="father">
            {{'我是父组件'}}
            <son :text="text"></son> 
        </div>
    </template>
    <script>
        import son from './son.vue'
        export default {
            data(){
                return{
                    text:'这个是从父组件传来的数据'
                }
            },
            components:{
                son:son
            }
        }
    
    </script>
    <style>
        
    
    </style>

    son.vue

    <template>
        <div class="son">
            {{'我是子组件'+text}}    
        </div>
    </template>
    <script>
        export default{
            props:{
                text:{type:String,default:''}
            }
        }
    </script>
    <style>
        
    </style>

    子组件向父组件传值

    father.vue

    <template>
        <div class="father">
            {{'我是父组件名称: '+name}}
            <son :changeName="changeName"></son> 
        </div>
    </template>
    <script>
        import son from './son.vue'
        export default {
            data(){
                return{
                    name:'父组件'
                }
            },
            methods:{
                changeName(newname){
                    this.name = newname;
                }
            },
            components:{
                son:son
            }
        }
    
    </script>
    <style>
        
    
    </style>

    son.vue

    <template>
        <div class="son">
            {{'我是子组件button'}}
            <button @click="()=>changeName(tname)">
                 修改父组件名称哈哈哈
            </button>    
        </div>
    </template>
    <script>
        export default{
            data(){
                return {
                    tname:'哈哈哈'
                }
            },
            props:{
                changeName:{
                    type:Function,
                    default: ()=>{ }
                }
            }
        }
    </script>
    <style>
        
    </style>

    通过子组件props把 changName方法传递父组件

    感谢作者 http://www.cnblogs.com/penghuwan/p/7286912.html

  • 相关阅读:
    正则表达式
    Ajax跨域问题---jsonp
    Ajax
    字符串总结
    js 字符串加密
    jsDate()
    HDU 5430 Reflect
    HDU 5429 Geometric Progression
    HDU 5428 The Factor
    POJ 2485 Highways
  • 原文地址:https://www.cnblogs.com/junwu/p/7326459.html
Copyright © 2020-2023  润新知