学习优先度:★★★★★

难易度:★★★★☆

每个 Vue 组件本质上都是一个可重用的实例,拥有自己的数据、方法和生命周期。

在 Vue.js 中,组件是封装了自己的数据、方法和生命周期钩子的可重用实例。这种模块化方法可以更好地组织代码并提高可重用性。

【代码示例】

// Define a new component called 'my-component'
Vue.component('my-component', {
 // The component's data function returns an object
 data: function() {
  return {
   message: 'Hello from my component!'
  }
 },
 // The template defines the HTML structure
 template: '<div>{{ message }}</div>',
 // Lifecycle hook: called when the component is created
 created: function() {
  console.log('Component has been created!');
 },
 // Method to update the message
 methods: {
  updateMessage: function(newMessage) {
   this.message = newMessage;
  }
 }
});
// Create a new Vue instance and mount it to the #app element
new Vue({
 el: '#app'
});

【执行结果】

textComponent 已创建!

在这个示例中,my-component 被定义了自己的数据、模板和方法。数据函数返回一个包含组件状态的对象。模板定义了 HTML 结构,创建的生命周期钩子会在组件创建时记录一条信息。methods 属性包含可用于修改组件数据的函数。

创建 Vue 实例并将其挂载到 #app 元素后,就可以在 Vue 实例的 HTML 中使用该组件。每次使用 my-component 时,都会创建一个拥有自己数据和生命周期的新实例。

【补充】

Vue 组件之间可以使用道具和事件进行通信。道具允许父组件向子组件传递数据,而事件允许子组件向父组件发送信息。这使得 Vue 组件具有高度的模块化和可重用性。