在 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 來控制公共組件實現的步驟。