Vue函数式调用组件创建公共组件

2020-01-16 08:52:22

参考地址 Vue——函数式调用组件

正常情况下使用组件


  import 组件

import xxx from 'XXXx/XXX.vue'

注册组件

export default {

    components:{

      XXX

    },

}

然后再使用组件以及配置,如果要显示这个组件就要改别isShow的值

<template>

    <div>

        <xxx :show="isShow" text="hello"></xxx>

    </div>

</template>

所有组件都需要这么去调用,就会有些许麻烦而且不太美观。像Loading、Toast等这些组件,一页面可以经常用到而且每次显示的内容都可能不一样,这样的话用js的方式【this.$xxx.show(option)】去调用就方便很多,而且代码也更整洁。


实现

以Loading组件为例,先创建好loading组件



创建一个loading.js,并在里面引入组件以及Vue

import Vue from 'vue'

import Loading from 'loading.vue'

实例化Vue,并用render函数创建组件模板

const v = new Vue({

    render(createElement){

        return createElement(Loading) 

    }

})

渲染DOM,并挂载到body里

v.$mount() //渲染

 

document.body.appendChild(v.$el) //挂载

获取组件的实例

const load = v.$children[0]

定义需要被暴露的接口

//显示loading弹窗

function showLoading(opt){

    //load相当于是在Loading.vue当中的this

    //showLoading()就是methons中的函数

    load.showLoading(opt)

}

 

export default {

    showLoading

}

最后在mian.js中引入,并且挂到Vue的原型里

import Vue from 'vue'

import loading from './component/Loading.vue'

 

Vue.prototype.$loading = loading

调用loading

<template>

   <div>

       <button @click="load">Loading</button>

   </div>

</template>

<script>

export default {

   name:'test',

   data () {

      return {}

   },

   methods: {

      load(){

         this.$loading.showLoading({

            info:'加载中'

         })

      }

   }

}

</script>

效果:



  • 2017-02-09 09:02:26

    两列布局——左侧宽度固定,右侧宽度自适应的两种方法

     关于左侧宽度固定,右侧宽度自适应两列布局的一种很常用的方法我相信大家都知道。就是利用左侧元素浮动,或者绝对定位的方式使其脱离常规文档流,让两个块级元素能够在同一行显示。然后右侧元素 margin-left 的值等于左侧元素宽度,这时右侧元素将紧挨着左侧元素

  • 2017-02-10 15:19:51

    Git:代码冲突常见解决方法

    如果系统中有一些配置文件在服务器上做了配置修改,然后后续开发又新添加一些配置项的时候, 在发布这个配置文件的时候,会发生代码冲突:

  • 2017-02-10 15:24:14

    linux学习之——vim简明教程

    学习 vim 并且其会成为你最后一个使用的文本编辑器。没有比这个更好的文本编辑器了,非常地难学,但是却不可思议地好用。 我建议下面这四个步骤: 存活 感觉良好 觉得更好,更强,更快 使用VIM的超能力

  • 2017-02-10 16:22:13

    git历史记录查询

    查看提交历史:git log 查看提交历史并显示版本间的差异:git log -p 查看指定历史:git log xxx(sha1值) -p 查看提交历史(指定时间):

  • 2017-02-13 17:50:05

    cURL error 60: SSL certificate problem: unable to get local issuer certificate

    Drupal 8 version uses Guzzle Http Client internally, but under the hood it may use cURL or PHP internals. If you installed PHP cURL on your PHP server it typically uses cURL and you may see an exception with error Peer certificate cannot be authenticated with known CA certificates or error code CURLE_SSL_CACERT (60).