Vue 中自定义组件(包含实例)

本文介绍了Vue中自定义组件的定义、使用方法及一个点赞组件的实例。通过Vue.component()创建组件,然后在HTML中引用。在实际开发中,可以限制组件的作用域,并进行进一步封装。文中提供了一个<like>组件的详细实现过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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></alert>
</div>
<script src="alert.js"></script>
</body>
</html>

这样就简单完成了,但是这样只是最基本的原理,而且是全局实现,在实际开发中我们可能会针对某一个域使用。也可以这样定义:

new Vue({
	el: '#app',
	components: {
		alert: {
			template: '<button @click="onClick">弹窗</button>',
			methods:{
				onClick: function(){
					alert("Hello Vue!");
				}
			}
		}
	}
});

这样就实现了只在 app 中使用此组件。同时我们还可以把他再封装一下:

var Alert = {
	template: '<button @click="onClick">弹窗</button>',
	methods:{
		onClick: function(){
			alert("Hello Vue!");
		}
	}
};
new Vue({
	el: '#app',
	components: {
		alert: Alert
	}
});

实例

下面写一个点赞的组件 <like> 实例:

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<div id="app">
    <like></like>
</div>
<template id="like-component-tpl">
    <button :class="{liked: liked}" @click="like">赞{{like_num}}</button>
</template>
<style type="text/css">
    .liked{
        background-color: deeppink;
    }
</style>
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
<script type="text/javascript">
    var like_conponent = {
        template: '#like-component-tpl',
        data: function () {
            return{
                like_num: 1,
                liked: false,
            }
        },
        methods: {
            like: function () {
                if(!this.liked){
                    this.like_num++;
                }
                else{
                    this.like_num--;
                }
                this.liked = !this.liked;
            }
        }
    };
    new Vue({
        el: '#app',
        components: {
            like: like_conponent
        }
    });
</script>
</body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值