如何在JS文件中獲取Vue組件
1. 背景
最近在寫項(xiàng)目時候遇到這樣一個需求:
我封裝了一個js文件 utils.js,然后在組件 my-component.vue 中引用了該js文件。 在 utils.js 文件中有一些函數(shù),需要操作 my-component.vue 中的 data 和 methods。為了方便理解,上述 js 文件和組件名非實(shí)際工程中的名字,僅是示例。
2. 思路
通過調(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 中定義一個變量和一個函數(shù),該變量用于存放組件實(shí)例 this,該函數(shù)用于接收組件實(shí)例 this。
utils.js
// 用來存放調(diào)用此js的vue組件實(shí)例(this)let vm = nullconst sendThis = ( _this )=> { vm = _this}export default { sendThis, // 暴露函數(shù) description: ’我是一個工具類方法’, 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 傳過去即可。
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 實(shí)例原型上,自然也就可以在某個 js 文件中拿到 vue 實(shí)例了。
以上就是如何在JS文件中獲取Vue組件的詳細(xì)內(nèi)容,更多關(guān)于在JS文件中獲取Vue組件的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. Springboot Druid 自定義加密數(shù)據(jù)庫密碼的幾種方案2. 詳解Android studio 動態(tài)fragment的用法3. 解決Android studio xml界面無法預(yù)覽問題4. Spring Boot和Thymeleaf整合結(jié)合JPA實(shí)現(xiàn)分頁效果(實(shí)例代碼)5. 什么是python的自省6. Vuex localStorage的具體使用7. php模擬實(shí)現(xiàn)斗地主發(fā)牌8. Spring MVC+ajax進(jìn)行信息驗(yàn)證的方法9. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應(yīng)用實(shí)現(xiàn)10. 使用Android studio查看Kotlin的字節(jié)碼教程

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