vue 用 js 调用公共组件

在 vue 项目中,对于公共组件的调用一般是 import 引入公共组件,然后在 components 中注册组件,在页面中以标签的方式运用。

import Msg from './msg'

export default {
  ......
  components: {
    Msg
  },
  ......
}

如果是用 js 调用呢?

export default {
  ......,
  methods: {
    show() {
      this.$message({
        message: 'xxxxxx',
        type: 'success'
      })
    }
  },
  ......
}

实现:

1、先写好一个组件:

// msg.vue
<template> <div class="msg" v-if="isShow">msg component</div> </template> <script> export default { name: 'msg', data() { return { isShow: false } }, mounted() { this.fn1(2) }, methods: { show() { this.isShow = true console.log('show') }, hide() { this.isShow = false console.log('hide') } } } </script>

2、新建一个 js 文件:

// index.js
import Vue from 'vue' import Msg from './msg' const MsgConstructor = Vue.extend(Msg) const options = { data() { return { a: 1111111 } }, mounted() { this.fn1(1) }, methods: { fn1(val) { this.a = 3333 console.log('fn1', val) } }, watch: { a(val) { console.log('watch', val) } } } // options 内部同组件内部生命周期一样,但组件内部优先执行 const instance = new MsgConstructor(options) instance.$mount() document.body.appendChild(instance.$el) export default function install() { Vue.prototype.$msg = instance }

3、main.js 内引入:

// main.js
import Vue from 'vue' import App from './App.vue' import router from './router' // msg公共组件 import msg from '@/components' Vue.use(msg) Vue.config.productionTip = false new Vue({ router, render: h => h(App), }).$mount('#app')

4、页面内用法:

<!-- 页面内 -->

<template>
  <div class="hello">
    <button @click="$msg.show()">show</button>
    <button @click="$msg.hide()">hide</button>
  </div>
</template>

上面就完成了用纯 js 来控制公共组件实现的步骤。

原文地址:https://www.cnblogs.com/kdcg/p/13477448.html