Vue的组件和父子组件的通信

今天我学习了Vue的组件和父子组件的通信。Vue的组件可以将整个应用划分为多个可复用的部分,每个组件都可以包含模板、数据和行为。在Vue中,组件可以被定义为一个扩展了Vue构造函数的对象:

Vue.component('my-component', {

  template: '<div>{{ message }}</div>',

  data: function() {

    return {

      message: 'Hello from the component!'

    }

  }

})

 

然后在html中使用自定义标签调用该组件:

<my-component></my-component>

 

父子组件之间的通信可以通过事件和props属性实现,例如父组件可以通过props把数据传递给子组件:

Vue.component('child-component', {

  props: ['message'],

  template: '<div>{{ message }}</div>'

})

 

var app = new Vue({

  el: '#app',

  data: {

    parentMessage: 'Hello from the parent component!'

  }

})

 

html中使用子组件并将数据传递进去:

<child-component :message="parentMessage"></child-component>

 

明天我将继续学习Vue的路由和HTTP请求。

posted @ 2023-05-25 11:03  ITJAMESKING  阅读(25)  评论(0编辑  收藏  举报