VUE 学习之父子之间数据传递

目前父子组件数据传递一般是: 父组件通过props向子组件进行传递数据,子组件通过$emit方法向父组件发送数据,父组件监听子组件发送过来的数据。 

 

<div id="app">
    <child-comp
      :parent-msg="parentMsg()"
      @child-event="handleChildEvent"
    ></child-comp>
</div>

 

Vue.component('child-comp', {
    template: "<div><button @click='sendMsgToParent'>send msg to parent</button></div>",
    data: function () {
        return {
            childMsg: 'Hello, I am Child'
        }
    },
    props: ['parentMsg'],
    methods: {
        sendMsgToParent(){

            this.$emit("child-event", this.childMsg);
        }
    },
    mounted () {
        console.log('child mounted, parent msg: ' + this.parentMsg)
    }
});
const app = new Vue({
    el: '#app',
    data: function () {
        return {
            parentData : "parent Message"
        }
    },
    methods: {
        parentMsg(){
            return this.parentData;
        },
        handleChildEvent(event){
            console.log("the msg from child: " + event);
        }
    }
})

 

这个例子实例动态绑定了parent-msg 通过props传递给了子组件。 在子组件中的button 点击事件中发送子组件中的数据给父组件。

 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中,父子组件之间可以通过props和$emit来实现数据的共享。 1. 使用props传递数据: 父组件可以通过props属性将数据传递给子组件。在子组件中,可以通过props选项接收父组件传递数据,并在子组件中使用。 ```vue // 父组件 <template> <div> <child-component :message="message"></child-component> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { message: 'Hello from parent component' }; } }; </script> // 子组件 <template> <div> <p>{{ message }}</p> </div> </template> <script> export default { props: ['message'] }; </script> ``` 2. 使用$emit触发事件: 子组件可以通过$emit方法触发一个自定义事件,并将数据作为参数传递给父组件。在父组件中,可以通过监听子组件触发的事件来获取子组件传递数据。 ```vue // 父组件 <template> <div> <child-component @message-updated="updateMessage"></child-component> <p>{{ message }}</p> </div> </template> <script> import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, data() { return { message: '' }; }, methods: { updateMessage(newMessage) { this.message = newMessage; } } }; </script> // 子组件 <template> <div> <button @click="sendMessage">Send Message</button> </div> </template> <script> export default { methods: { sendMessage() { this.$emit('message-updated', 'Hello from child component'); } } }; </script> ``` 这样,父组件就可以通过props接收子组件传递数据,子组件也可以通过$emit触发事件将数据传递给父组件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值