V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
allzc
V2EX  ›  Vue.js

vue 局部注册插件可行?

  •  
  •   allzc · 2022-06-22 16:19:20 +08:00 · 1116 次点击
    这是一个创建于 645 天前的主题,其中的信息可能已经有所发展或是发生改变。

    组件 A 里面使用了第三方插件 组件 B 里面使用了原生代码方式去做 但现在这两种方式冲突了 导致第一次加载的时候 组件 B 出问题了 因为在 main.js 中 vue.use(插件) 全局引入了 我想知道可不可以在部分组件里使用插件 这种方式没试过 只用过局部注册组件 没尝试过局部注册插件 大神指点迷津

    2 条回复    2022-06-23 10:31:19 +08:00
    yangheng4922
        1
    yangheng4922  
       2022-06-22 23:14:38 +08:00
    好像 Vue.use 是直接在 prototype 上注入的 应该不能局部吧
    Ccbeango
        2
    Ccbeango  
       2022-06-23 10:31:19 +08:00
    可以实现。文档中也说了,插件通常用来为 Vue 添加全局功能。所以,当然也可以实现局部的。
    插件功能见文档: https://cn.vuejs.org/v2/guide/plugins.html
    我只用了 Vue2 做了一种测试,添加 Vue 实例方法,通过把它们添加到 Vue.prototype 上实现。

    在 Vue 中注册插件时通过 Vue.use()进行注册。创建子组件时,可以通过 Vue.extend()来创建 Vue 的子构造函数,内部其实时通过寄生式组合继承实现的。那么,首先通过 Vue.extend()来创建子组件,再通过子组件调用 use 方法就能实现局部注册。

    如下:
    <html>
    <head>
    <title>Hello Vue</title>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
    </head>
    <body>
    <div id="app"></div>
    <script>
    let A = Vue.extend({
    template: '<div @click="test">{{msg}}</div>',
    data() {
    return {
    msg: '我是孙子组件,点击我触发局部注册的方法$myTest'
    }
    },
    methods: {
    test() {
    this.$myTest()
    }
    }
    })

    A.use({
    install(Vue, options) {
    Vue.prototype.$myTest = function() {
    console.log('myTest...')
    }
    }
    })

    let childComp = {
    template: '<div>{{msg}}<A/></div>',
    components: {
    A
    },
    props: {
    info: String
    },
    data() {
    return {
    msg: '我是子组件'
    }
    },
    created() {
    console.log('child created')
    },
    mounted() {
    console.log('child mounted')
    }
    }

    Vue.mixin({
    data () {
    return {
    hello: 'world'
    }
    },
    created() {
    console.log('mixin parent created')
    }
    })

    let app = new Vue({
    el: '#app',
    template: `<div><h1 @click="test">{{msg}}</h1><childComp/></div>`,
    data: {
    msg: '我是父组件,点我会报错找不到'
    },
    components: {
    childComp
    },
    methods: {
    test() {
    this.$myTest()
    }
    }
    })
    </script>
    </body>
    </html>
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   981 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 24ms · UTC 22:08 · PVG 06:08 · LAX 15:08 · JFK 18:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.