美文网首页
vue父子组件之间传值

vue父子组件之间传值

作者: 男人宫 | 来源:发表于2021-06-09 14:43 被阅读0次

    父组件向子组件传值是通过属性(props)的形式进行传递
    子组件向父组件传值是通过事件($emit)的形式进行传递.也可以理解成通过事件回调的方式(自己理解的)

    父子之间传递

    //父组件代码如下:

    <template>
        <div>
            <one-component :name="message" @receivedata="changesome"></one-component>
        </div>
    </template>
    
    <script>
    
     import OneComponent from "./OneComponent.vue"
     export default {
        name:"HelloWorld",
        data() {
            return {
                message:"Hellow World!!!!!!"
            }
        },
        components:{
            OneComponent
        },
         methods: {
        changesome(num){
          console.log(`我是父组件,有人向我发消息传的值是${num}`);
        }
      },
    }
    </script>
    
    <style scoped>
        
    </style>
    
    

    子组件代码如下:

    <template>
        <div>
            <p>我想对这个世界说:{{name}}</p>
            <button @click="clickme">click</button>
        </div>
    </template>
    
    <script>
    export default {
        name:"OneComponent",
        props:["name"],
        methods: {
            clickme(){
              console.log("我是子组件");
              this.$emit("receivedata",200);
            }
        },
    }
    </script>
    
    </style>
    

    相关文章

      网友评论

          本文标题:vue父子组件之间传值

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