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>

效果:



  • 2020-08-16 16:09:30

    android WebView 注入js 几种方式

    有时我们开发中需要将js 注入到我们本地,有可能你会说,放在Web不就可以了吗,的确,但是需求就是这样的

  • 2020-11-05 23:20:29

    mac更新node版本

    initializer function 0x0 not in mapped image for /usr/local/bin/node,除了上面的问题 你或许还出现过 no such file or directory 这样的提示,总之更新完以后node直接不能用了。

  • 2020-11-07 16:31:02

    nginx配置X-Frame-Options允许多个域名iframe嵌套

    有时候我们需要允许多个url的来源,但是又不能全部开放,所以应该匹配第三种方法ALLOW-FROM url,那么多个url该如何配置呢,百度了所有网站都没有找到,那么这里写给大家,其实很简单: add_header X-Frame-Options 'ALLOW-FROM https://xxx.xxxxxx.com https://xxx2.xxxxxxx.com'; 就是使用空格隔开就好了!

  • 2020-11-08 08:31:51

    meteor在不同端口启动服务

    当没有任何参数时,run是默认行为,在幕后,它3000端口开启node.js服务器实例,同时开启监听3001端口的MongoDB服务