如何在JS文件中獲取Vue組件
1. 背景
最近在寫項(xiàng)目時(shí)候遇到這樣一個(gè)需求:
我封裝了一個(gè)js文件 utils.js,然后在組件 my-component.vue 中引用了該js文件。 在 utils.js 文件中有一些函數(shù),需要操作 my-component.vue 中的 data 和 methods。為了方便理解,上述 js 文件和組件名非實(shí)際工程中的名字,僅是示例。
2. 思路
通過(guò)調(diào)用函數(shù)把 組件實(shí)例 this 傳遞到 被應(yīng)用的 js 文件 里。
3. 目錄結(jié)構(gòu)
src/├── App.vue├── assets├── main.js├── components└── views └── demo ├── my-component.vue └── utils.js
4. 代碼實(shí)現(xiàn)
在 utils.js 中定義一個(gè)變量和一個(gè)函數(shù),該變量用于存放組件實(shí)例 this,該函數(shù)用于接收組件實(shí)例 this。
utils.js
// 用來(lái)存放調(diào)用此js的vue組件實(shí)例(this)let vm = nullconst sendThis = ( _this )=> { vm = _this}export default { sendThis, // 暴露函數(shù) description: ’我是一個(gè)工具類方法’, getData() { console.log(vm) // 打印拿到的組件實(shí)例 console.log(vm.userProfile) // 打印組件中的data }, callMethod() { vm.clearForm() // 調(diào)用組件中的methods }}
在 my-component.vue 中引入 utils.js,然后在鉤子函數(shù)中調(diào)用 utils.js 的 sendThis 方法,把 this 傳過(guò)去即可。
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: { // 這個(gè)函數(shù)會(huì)在 utils.js 文件中被調(diào)用 clearForm() { // 執(zhí)行一些操作 }, // 打印 utils.js 中的 description showMsg() { console.log(utils.description) } }}</script>
5. 其它思路
還有一種思路:
把一些屬性和方法掛載到 vue 實(shí)例原型上,自然也就可以在某個(gè) js 文件中拿到 vue 實(shí)例了。
以上就是如何在JS文件中獲取Vue組件的詳細(xì)內(nèi)容,更多關(guān)于在JS文件中獲取Vue組件的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. PHP使用Swagger生成好看的API文檔2. ASP.NET MVC使用jQuery ui的progressbar實(shí)現(xiàn)進(jìn)度條3. Python3 json模塊之編碼解碼方法講解4. Python 制作查詢商品歷史價(jià)格的小工具5. Python 如何調(diào)試程序崩潰錯(cuò)誤6. Python 利用Entrez庫(kù)篩選下載PubMed文獻(xiàn)摘要的示例7. ASP基礎(chǔ)知識(shí)VBScript基本元素講解8. python使用jenkins發(fā)送企業(yè)微信通知的實(shí)現(xiàn)9. Python sublime安裝及配置過(guò)程詳解10. Python 合并拼接字符串的方法

網(wǎng)公網(wǎng)安備