JavaScript

超轻量级php框架startmvc

Vue组件全局注册实现警告框的实例详解

更新时间:2020-07-12 23:36:01 作者:startmvc
外部引入<linkhref="https://cdn.bootcss.com/animate.css/3.5.2/animate.min.css"rel="stylesheet"><linkhref="ht

外部引入


<link href="https://cdn.bootcss.com/animate.css/3.5.2/animate.min.css" rel="stylesheet">
<link href="https://cdn.bootcss.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script type="text/javascript" src="../js/vue-2.5.16.js"></script>

HTML部分


 <div class="container">
 <!--动态数据绑定-->
 <my-info v-bind:data='msg' v-on:close='closeHandler'></my-info>
 <!--静态数据绑定-->
 <my-info data="操作有误"></my-info>
 </div>

script部分


<script type="text/javascript">
 Vue.component('my-info',{
 template:`
 <transition leave-active-class="animated fadeOutUpBig">
 <div
 v-show='isShow' 
 style="background:orange;
 color:#fff;
 padding:.5em 1em; 
 border-radius:5px; 
 margin:.5em 0; 
 position:relative">
 <i class="fa fa-info-circle"></i>
 <span>{{data}}</span>
 <i @click='close' class="fa fa-close" 
 style="position:absolute; 
 right: 1em;
 cursor:pointer"></i>
 </div>
 </transition>
 `,
 //注意:data必须是一个函数
 data(){
 return {
 isShow:true
 }
 },
 props:['data'],
 methods:{
 close(){
 //子组件向父组件发射事件
 this.$emit('close');
 //关闭消息框
 this.isShow = false;
 }
 },
 });
 new Vue({
 el:'.container',
 data:{
 msg:'添加失败!'
 },
 methods:{
 closeHandler(){
 console.log('关闭了');
 }
 }
 });
 </script>

效果

全局组件

组件的创建和注册分成3步:创建组件构造器,注册组件,挂载作用域内实例化

例如:


<div id="app">
 <!-- 3. #app是Vue实例挂载的元素,应该在挂载元素范围内使用组件-->
 <my-component></my-component>
</div>
<script>
 // 1.创建一个组件构造器
 var myComponent = Vue.extend({
 template: '<div>这是我的全局组件</div>'
 })
 
 // 2.注册组件,并指定组件的标签,组件的HTML标签为<my-component>
 Vue.component('my-component', myComponent)
 
 new Vue({
 el: '#app'
 });
</script> 

我们来理解组件的创建和注册:

  1. Vue.extend()是Vue构造器的扩展,调用Vue.extend()创建的是一个组件构造器,而不是一个具体的组件实例。
  2. Vue.extend()构造器有一个选项对象,选项对象的template属性用于定义组件要渲染的HTML。
  3. 使用Vue.component()注册组件时,需要提供2个参数,第1个参数时组件的标签,第2个参数是组件构造器,也就是说
  4. Vue.component('标签名',Vue.extend())=>
  5. Vue.component('标签名', {template:' '})
  6. Vue.component()方法内部会调用组件构造器,创建一个组件实例。

全局组件必须写在Vue实例创建之前,才在该根元素下面生效

例如:


<div id="app">
 <!--该组件不会被渲染,并且报错-->
 <my-component></my-component>
 </div>
 <div id="app1">
 <my-component></my-component>
 </div>
 <script>
 new Vue({
 el: "#app"
 });
 Vue.component("my-component", {
 template: "<h1>这是我的全局组件</h1>"
 });
 new Vue({
 el: "#app1"
 })
 </script> 

Prop传值

组件实例的作用域是孤立的,父组件可以通过props向下传递数据给子组件。

Prop静态传递数据


<div class="father"> 
 <child msg="hello!" data="yes!"></child> 
</div> 
Vue.component('child',{
 props:['msg',"data"],
 template:`<p>{{msg}}</p>
 <p>{{data}}</p>
 `
})

Prop动态传递数据


<div class="father"> 
 <child v-bind:msg="val"></child> 
</div> 
Vue.component('child',{
 props:["msg"],
 template:` <p>{{msg}}</p>`
})
new Vue({
 el:'.father,
 data:{
 val:'添加失败!'
 }
})

总结

以上所述是小编给大家介绍的Vue组件全局注册实现警告框的实例详解,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

vue组件全局注册 vue 警告框