学习优先度:★★★★★

难易度:★★★☆☆

在 Vue.js 中,组件是应用程序的基本构件。组件可帮助您将用户界面分割成独立、可重用的部分,并孤立地考虑每个部分。

让我们创建一个可在应用程序不同部分重复使用的 Vue 组件。

【代码示例】

<!DOCTYPE html> 
<html> 
<head> 
  <title>Vue.js Components</title> 
    <script src="https://cdn.jsdelivr.net/npm/vue@2"></script> 
</head> 
<body> 
    <div id="app"> 
​    <my-component></my-component> 
​    <my-component></my-component> 
  </div> 
    <script> 
​    // Define a new component called 'my-component' 
​    Vue.component('my-component', { 
​      template: '<div>A custom component!</div>' 
​    }); 
​    // Create a new Vue instance 
​    new Vue({ 
​      el: '#app' 
​    }); 
  </script> 
</body> 
</html> 

【执行结果】

The page displays "A custom component!" twice because we used the <my-component></my-component> tag twice in the HTML. 

在本例中,我们使用 Vue.component 定义了一个名为 my-component 的新组件。模板属性指定了将为该组件呈现的 HTML。通过在 HTML 中包含 <my-component></my-component>,我们可以多次重复使用该组件。Vue 中的组件还可以接受道具、发出事件并包含自己的数据和方法。

【补充】

Vue 组件可以是全局的,也可以是本地的。全局组件使用 Vue.component 注册,可在 Vue 实例的任何地方使用。本地组件在特定的 Vue 实例或其他组件中注册,只能在该范围内使用。