如何在JS文件中獲取Vue組件
1. 背景
最近在寫項目時候遇到這樣一個需求:
我封裝了一個js文件 utils.js,然后在組件 my-component.vue 中引用了該js文件。 在 utils.js 文件中有一些函數(shù),需要操作 my-component.vue 中的 data 和 methods。為了方便理解,上述 js 文件和組件名非實際工程中的名字,僅是示例。
2. 思路
通過調(diào)用函數(shù)把 組件實例 this 傳遞到 被應(yīng)用的 js 文件 里。
3. 目錄結(jié)構(gòu)
src/├── App.vue├── assets├── main.js├── components└── views └── demo ├── my-component.vue └── utils.js
4. 代碼實現(xiàn)
在 utils.js 中定義一個變量和一個函數(shù),該變量用于存放組件實例 this,該函數(shù)用于接收組件實例 this。
utils.js
// 用來存放調(diào)用此js的vue組件實例(this)let vm = nullconst sendThis = ( _this )=> { vm = _this}export default { sendThis, // 暴露函數(shù) description: ’我是一個工具類方法’, getData() { console.log(vm) // 打印拿到的組件實例 console.log(vm.userProfile) // 打印組件中的data }, callMethod() { vm.clearForm() // 調(diào)用組件中的methods }}
在 my-component.vue 中引入 utils.js,然后在鉤子函數(shù)中調(diào)用 utils.js 的 sendThis 方法,把 this 傳過去即可。
my-component.vue
<template> <div class='my-component'></div></template><script>import utils from ’./utils’export default { name: ’MyComponent’, data() { return { userProfile: ’’ } }, mounted() { // 發(fā)送this 到 js 文件里 utils.sendThis(this); }, methods: { // 這個函數(shù)會在 utils.js 文件中被調(diào)用 clearForm() { // 執(zhí)行一些操作 }, // 打印 utils.js 中的 description showMsg() { console.log(utils.description) } }}</script>
5. 其它思路
還有一種思路:
把一些屬性和方法掛載到 vue 實例原型上,自然也就可以在某個 js 文件中拿到 vue 實例了。
以上就是如何在JS文件中獲取Vue組件的詳細內(nèi)容,更多關(guān)于在JS文件中獲取Vue組件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Python實現(xiàn)迪杰斯特拉算法過程解析2. 詳解java中static關(guān)鍵詞的作用3. 詳解Python模塊化編程與裝飾器4. 基于Android FileProvider 屬性配置詳解及FileProvider多節(jié)點問題5. Python如何進行時間處理6. 關(guān)于Java下奇怪的Base64詳解7. vue+echarts實現(xiàn)中國地圖流動效果(步驟詳解)8. Java14發(fā)布了,再也不怕NullPointerException了9. python使用ctypes庫調(diào)用DLL動態(tài)鏈接庫10. python裝飾器三種裝飾模式的簡單分析
