zoukankan      html  css  js  c++  java
  • Vue组件封装(以封装一个button组件为例)

    1/在components文件内创建一个button文件,文件内创建一个index.vue文件,在index.vue文件内写的是原型(包含组件的名字,应用的最底层的HTML标签,分别根据什么条件显示什么功能),同时该文件导出的数据为一个对象。

     1 <template>
     2     <div :class="type == 'Default'?'btn default':type == 'primary'?'btn primary':type == 'danger'?'btn danger':'btn default'">
     3         <slot></slot>
     4     </div>
     5 </template>
     6 
     7 <script>
     8 export default {
     9     name:"alley-Button",
    10     props:{
    11         type:{
    12             type:String,
    13             default:"Default"
    14         }
    15     }
    16 }
    17 </script>
    18 
    19 
    20 <style>
    21     .btn{
    22           100px;
    23          height: 40px;
    24          color:#fff;
    25          text-align: center;
    26          line-height:40px;
    27     }
    28     .default{
    29        
    30         background: red;
    31        
    32     }
    33 
    34      .primary{
    35       
    36         background: yellow;
    37     }
    38 
    39      .danger{
    40      
    41         background: #ccc;
    42     }
    43 </style>

    2/在button文件下建立一个index.js文件,文件内对新构建组件的名字进行注册。

    1 import Button from "./index.vue";
    2 
    3  Button.install = (Vue)=>{
    4     Vue.component(Button.name,Button)
    5 }
    6 
    7 export default Button;

    3/ 与button文件同级建立一个index.js文件,对组件进行注册,同时也注册进install中,在导出时,不仅要引出全局的,而且单个的也要引出,便于局部或全局引用。

     
     1 import Button from "./button"
     2  3  4  const components = [
     5      Button
     6  ]
     7  8  9  //vue。use使用时,必须要有install方法。参数就是vue。
    10  const install  = (Vue)=>{
    11      for(var key in components){
    12          Vue.component(components[key].name,components[key])
    13      }
    14  }
    15 16 17  export default {
    18      install,
    19      Button
    20  }

    4/要在main.js中进行引用

    1  import Vue from 'vue'
    2  import App from './App.vue'
    3  import AlleyUI from "./components"
    4  Vue.config.productionTip = false
    5  Vue.use(AlleyUI);
    6 7  new Vue({
    8    render: h => h(App),
    9  }).$mount('#app')

    5/到这里,组件便是封装完成了,在App.vue中可以进行使用了。

     
     1 <template>
     2    <div id="app">
     3      <alley-Button>按钮</alley-Button>
     4      <alley-Button type="primary">按钮</alley-Button>
     5      <alley-Button>按钮</alley-Button>
     6      <alley-Button>按钮</alley-Button>
     7    </div>
     8  </template>
     9 10  <script>
    11 12  export default {
    13    name: 'app',
    14   
    15  }
    16  </script>
    17 18  <style>
    19 20  </style>

    6/ 运行结果为

     

  • 相关阅读:
    JSP(工作原理,组成部分,指令标签,动作标签,隐式对象)
    会话技术cookie与session
    上下文对象-请求对象-响应对象(ServletContext
    反射
    Servlet
    Tomcat服务器
    Http协议
    客户端与服务器
    Oracle虚拟机 与 windows配置
    SQL语句简单整理
  • 原文地址:https://www.cnblogs.com/muzishijie/p/11291295.html
Copyright © 2011-2022 走看看