目录1. 概述2. 全局组件2.1 不使用组件的写法2.2 使用组件2.3 组件中包含变量2.4 组件的复用2.5 组件中使用组件2.6 总结3. 局部组件3.1 局部组件的使用3.
老话说的好:忍耐是一种策略,同时也是一种性格磨炼。
言归正传,今天我们来聊聊 VUE 的全局组件与局部组件。
<body>
<div id="myDiv"></div>
</body>
<script>
const app = Vue.createApp({
template:`
<div>
<div>hello</div>
<div>zhuifengren</div>
</div>
`
});
const vm = app.mount("#myDiv");
这是我们之前不使用组件的写法,接下来我们用组件去实现相同的效果。
const app = Vue.createApp({
template:`
<div>
<hello-com />
<zhuifengren-com />
</div>
`
});
app.component('hello-com', {
template: `
<div>hello</div>
`
});
app.component('zhuifengren-com', {
template: `
<div>zhuifengren</div>
`
});
我们把之前的<div>hello</div> 和<div>zhuifengren</div> 分别封装在了组件中,然后直接将组件名作为标签即可。
组件名称的命名规范:建议使用全小写字母,单词之间使用 “-” 连接。
const app = Vue.createApp({
template:`
<div>
<count-com />
</div>
`
});
app.component('count-com', {
data() {
return {
count : 1
}
},
template: `
<div>{{count}}</div>
<button @click="count += 1">加1</button>
`
});
const app = Vue.createApp({
template:`
<div>
<count-com />
<count-com />
<count-com />
</div>
`
});
从这个例子能看出来,组件的好处就是可以复用,且组件中的变量是独享的。
const app = Vue.createApp({
template:`
<div>
<count-com />
<count-com />
<count-com />
<count-com-2 />
</div>
`
});
app.component('count-com-2', {
template: `
<count-com />
`
});
我们在另一个组件 count-com-2 中使用 count-com 组件,也是可以的。
全局组件,使用起来很简单,只需要使用 app.component 函数声明一下即可。
一个全局组件可以被另一个全局组件使用。
但全局组件,只要声明,即使不使用也会被初始化,影响性能。
<body>
<div id="myDiv"></div>
</body>
<script>
const CountCom = {
data() {
return {
count : 1
}
},
template: `
<div>{{count}}</div>
<button @click="count += 1">自增</button>
`
}
const app = Vue.createApp({
// 组件映射
components : {
'count-com': CountCom
},
template:`
<div>
<count-com/>
</div>
`
});
const vm = app.mount("#myDiv");
局部组件的写法是,首先声明一个对象,内容和全局组件类似,然后将组件与对象做一个映射。
局部组件声明的对象建议首字母大写,单词间使用驼峰命名。
映射时,组件的名称还保持全小写字母,单词之间使用 “-” 连接。
局部组件,如果不使用,就不会初始化,因此对性能有好处。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>组件的分类</title>
<script src="js/vue.js"></script>
</head>
<body>
<div id="itany">
<my-hello></my-hello>
<my-world></my-world>
</div>
<script>
Vue.component('my-hello',{
template:'<h3>{{name}}</h3>',
data:function(){ //在组件中存储数据时,必须以函数形式,函数返回一个对象
return {
name:'alice'
}
}
});
var vm=new Vue({
el:'#itany',
data:{
name:'tom'
},
components:{ //局部组件
'my-world':{
template:'<h3>{{age}}</h3>',
data(){
return {
age:25
}
}
}
}
});
</script>
</body>
</html>
今天聊了一下 vue3 的 全局组件与局部组件,希望可以对大家的工作有所帮助
到此这篇关于VUE3学习教程之全局组件和局部组件的文章就介绍到这了,更多相关VUE3全局组件和局部组件内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!
--结束END--
本文标题: VUE3学习教程之全局组件和局部组件
本文链接: https://www.lsjlt.com/news/162931.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0