一、全局组件的注册方法
1)直接使用Vue.component
# index.js
Vue.component('my-component',{
template:'<h1>我是全局组件</h1>'
});
new Vue({
el:"#app"
});
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my vue learn</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app"><my-component></my-component></div>
<script src="index.js"></script>
</body>
</html>
2)使用Vue.extend配合Vue.component
#index.js
var com1 = Vue.extend({
template:'<h1>我是全局组件</h1>'
})
Vue.component('my-component', com1);
new Vue({
el:"#app"
});
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my vue learn</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app"><my-component></my-component></div>
<script src="index.js"></script>
</body>
</html>
3)Vue外部定义template
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my vue learn</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app">
<my-com3></my-com3>
</div>
<template id="tmp1">
<div>
<h2>这是通过template元素,在外部定义组件的结构,有代码的提示和高亮</h2>
</div>
</template>
<script>
Vue.component('myCom3', {
template: "#tmp1"
});
var vm = new Vue({
el: '#app',
data: {},
methods: {}
});
</script>
</body>
</html>
二、局部组件
#index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>my vue learn</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
<div id="app1">
<child-component></child-component>
</div>
<script>
var child={
template:"<h1>我是局部组件</h1>"
};
new Vue({
el: "#app1",
components:{
"child-component":child
}
});
</script>
</body>
</html>
网友评论