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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM