Vue 支持自定义组件,方便我们在开发过程中根据自己的项目自定义组件。
定义
主要是通过 Vue.component( ) 来完成。新建一个 alert.js 文件:
// 自定义一个 alert 组件
Vue.component('alert', {
template: '<button @click="onClick">弹窗</button>',
methods:{
onClick: function(){
alert("Hello Vue!");
}
}
});
new Vue({
el: '#app',
});
在上述例子中,template 中定义的是该组件的模板。
使用
引入 js 文件后,直接在 html 文件中使用:
<!doctype html>
<html lang="">
<head>
<title>Demo</title>
</head>
<body>
<div id="app">
<alert>