美文网首页
vue:use和prototype区别

vue:use和prototype区别

作者: 清远_03d9 | 来源:发表于2019-10-31 19:31 被阅读0次
  • 1、不是为了vue写的插件(插件内要处理)不支持Vue.use()加载方式
  • 2、非vue官方库不支持new Vue()方式
  • 3、每一个vue组件都是Vue的实例,所以组件内this可以拿到Vue.prototype上添加的属性和方法。


    6515740-571613462e27c1d7.png

1. 使用Vue.use()写一个自己的全局组件

目录结构

1. 在Loading.vue里面定义自己的组件模板

<template>
    <div v-if="loadFlag">
        Loading...
    </div>
</template>
<script>
    export default {
        name: "MyLoading",//组件名称
        props: ['loadFlag'],
    }
</script>

2. 在loading文件夹下的index.js文件里面添加install方法

import Loading from './Loading.vue'

Loading.install=function(Vue){
    Vue.component(Loading.name,Loading) //组件名称取组件的name
}

export default Loading  //导出组件

3. main.js引入

// 引入自定义组件。index.js是组件的默认入口
import Loading from '../components/common/loading'
Vue.use(Loading);

4. 在页面里面使用组件,这个组件已经在main.js定义加载了

<template>
    <div id="app">
        <!-- 使用自定义组件 -->
        <my-loading></my-loading>
    </div>
</template>
<script>
    export default {
        data() {
            return {
                loadFlag: true,
            }
        },
        created: function () {
            this.getTableData();
        },
        methods: {
            getTableData() {
                this.$http.post('.../').then(res => {
                    ...
                    this.loadFlag = false;
                });
            }
        }
    }
</script>

2. 所有的全局组件也可在一个js里定义,然后在main.js全局使用

如下图是common文件夹下的index.js


common的index.js

3. main.js中使用

import common from '@/components/common'
Vue.use(common);

4. Vue.prototype

使用Vue.prototype.$my_message = Message.install方法导入,调用时直接使用this.$my_message('这是一个message'),可参考“Vue 自定义全局消息框组件

相关文章

网友评论

      本文标题:vue:use和prototype区别

      本文链接:https://www.haomeiwen.com/subject/acczvctx.html