在Vue中,组件是可复用的Vue实例。它封装了自己的模板、数据、方法和样式等,可以在应用中多次使用。定义一个Vue组件可以通过Vue.component方法。代码讲解
<template id=”hello-template”>
<div>
<h2>Hello {{ name }}!</h2>
<button @click=”greet”>Greet</button> </div>
</template>
<script>Vue.component(‘hello’, { template: ‘#hello-template’, data() { return { name: ‘Vue’ } }, methods: { greet() { alert(‘Hello!’) } }})
</script>
在上述示例中,我们定义了一个名为Hello的Vue组件。该组件的模板是通过外部的元素定义的,将其内容作为组件的模板。该组件还定义了一个name数据属性和一个greet方法,可以在模板中使用。