本篇内容主要讲解“Vue组件是什么及怎么应用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue组件是什么及怎么应用”吧!什么是组件用面向对象的思维去理解Vue
本篇内容主要讲解“Vue组件是什么及怎么应用”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“Vue组件是什么及怎么应用”吧!
用面向对象的思维去理解Vue组件,可以将所有的事物都抽象为对象,而类或者说是组件,都具有属性和操作。
如抽取人类为组件,其基本的属性有姓名、年龄、国籍;基本的方法有吃饭、睡觉、跑步等。
<script>
export default {
name: "person",
props: {
name: {
type: String,
required: false,
default: "无名氏"
},
age: {
type: Number,
required: false,
default: 0
},
country: {
type: String,
required: false,
default: "地球人"
}
},
methods: {
eat() {
consloe.log("吃饭")
},
sleep() {
consloe.log("睡觉")
},
run() {
consloe.log("跑步")
}
}
}
</script>
在面向对象中,构造函数可以为类初始化全局变量,所以这种方式同样可以用在组件中
<person :age="20" :name=""小明"" :country=""中国人""></person>
组件封装了数据以及操作,有进则有出,我们不用关心组件内发生了什么,我们只需要结果和呈现出来的效果如何。
外界不可以直接访问使用或访问组件的属性,该如何做?
使用$emit自定义事件,可以实现外界获取组件属性。
<template>
...
<button @click="handleClick">点击</button>
</template>
<script>
export default {
name: "person",
methods: {
handleClick() {
this.$emit("getPerson", {
age: this.age,
name: this.name,
country: this.country
})
}
}
}
</script>
外界调用组件时添加自定义函数@getPerson
或v-on:click="getPerson"
<template>
<div>
<person :age="20" :name=""小明"" :country=""中国人"" @getPerson="getPerson"></person>
</div>
</template>
<script>
export default {
name: "test",
methods: {
getPerson(info) {
consloe.log(info)
}
}
}
</script>
在网页开发中,你可能会用到标签,而你可能会想到标签不可能在一个页面使用一次,可能是多次使用到。你还可能会想到因为不同的情况而自定义一些宽度、高度和颜色。
所以可以将标签相关的html代码和CSS封装到组件中,对外,我们暴露width、height和type参数。在使用时,因为不同的情况而需要自定义,那么传递参数即可。
<template>
<view
:style="{ width: width, height: height }"
:class="["owl-tag-" + type]"
class="owl-tag text-xs flex align-center justify-center"
>
<slot></slot>
</view>
</template>
<script>
name: "owl-tag",
props: {
// 可传入有效值为 primary | gray
type: {
type: String,
default: "primary"
},
width: {
type: String,
required: false
},
height: {
type: String,
required: false
}
}
</script>
<style>
.owl-tag {
border-radius: 8rpx;
padding: 6rpx 10rpx;
}
.owl-tag-primary {
color: white;
background-color: #87cefa;
}
.owl-tag-gray {
color: #81868a;
background-color: #f0f1f5;
}
</style>
这些工作做好了,一个组件就被我们定义好了。想用就调用,想改就传参,这就是组件的好处。
<template>
<owl-tag
:type=""primary""
:height=""45rpx""
:width=""120rpx""
>
官方帖
</owl-tag>
</template>
到此,相信大家对“Vue组件是什么及怎么应用”有了更深的了解,不妨来实际操作一番吧!这里是编程网网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!
--结束END--
本文标题: Vue组件是什么及怎么应用
本文链接: https://www.lsjlt.com/news/99063.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0