我们这一次来玩一下vue中如何来定义一个全局的组件,并且通过Vue.use()来使用
首先我们应该在我们项目里面创建一个组件alert.vue,你们在玩的时候就随意啦想叫什么就叫什么,看你们心情!
如图
alert中的代码为
<template>
// 定义了简单的结构
<div class="box" v-if="isShow">
// 假装当做提示信息 可以传递进来
<p>{{msg}}</p>
<button @click="close">关闭</button>
</div>
</template>
<script>
export default {
data () {
return {
msg:'',
isShow:true
}
},
methods: {
close(){
this.isShow = false
}
},
created () {
this.msg = this.text
this.isShow = this.hidden
},
// 通过props获取传递过来的值 text:提示信息 hidden 是否显示
props:['text','hidden']
}
</script>
<style lang='less'>
.box{
width:300px;
height:200px;
background: rgba(255, 255, 255, 1);
border-radius:10px;
position: fixed;
top:50%;
left:50%;
transform: translate(-50%,-50%);
border: 1px solid #ccc;
h2{
text-align: center;
}
p{
text-align: center;
}
button{
width:100px;
height:35px;
background: #ccc;
border-radius:5px;
display: block;
margin: 15px auto 0px auto;
}
}
</style>
接下来我们再在同级目录创建一个index.js
index.js
// 首先将 弹框组件引入进来
import Alert from "./alert.vue"
// 需要将组件暴露出去
export default {
// Vue.js 的插件应该有一个公开方法 install。这个方法的第一个参数是 Vue 构造器,第二个参数是一个可选的选项对象 说白了 就是需要一个install方法 最终 vue通过这个方法将组件安装上
install:function(Vue){
// 定义一个全局组件
Vue.component('alert',Alert)
}
}
如果用脚手架创建的项目,接下来就在main.js中引入inde.js并且use就ok了
main.js
import Alert from "./views/index"
Vue.use(Alert)
然后就可以在其他组件中使用了
<alert text="你又漂亮了" :hidden="true"></alert>
看完的如果对你有帮助希望收藏加关注啊!猴哥在这个里谢谢啦