如何在JS檔案中獲取Vue元件
阿新 • • 發佈:2020-09-17
1. 背景
最近在寫專案時候遇到這樣一個需求:
- 我封裝了一個js檔案
utils.js
,然後在元件my-component.vue
中引用了該js檔案。 - 在
utils.js
檔案中有一些函式,需要操作my-component.vue
中的data
和methods
。
為了方便理解,上述 js 檔案和元件名非實際工程中的名字,僅是示例。
2. 思路
通過呼叫函式把 元件例項 this 傳遞到 被應用的 js 檔案 裡。
3. 目錄結構
src/ ├── App.vue ├── assets ├── main.js ├── components └── views └── demo ├── my-component.vue └── utils.js
4. 程式碼實現
在 utils.js
中定義一個變數和一個函式,該變數用於存放元件例項 this
,該函式用於接收元件例項 this
。
utils.js
// 用來存放呼叫此js的vue元件例項(this) let vm = null const sendThis = ( _this )=> { vm = _this } export default { sendThis,// 暴露函式 description: '我是一個工具類方法',getData() { console.log(vm) // 列印拿到的元件例項 console.log(vm.userProfile) // 列印元件中的data },callMethod() { vm.clearForm() // 呼叫元件中的methods } }
在 my-component.vue
中引入 utils.js
,然後在鉤子函式中呼叫 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() { // 傳送this 到 js 檔案裡 utils.sendThis(this); },methods: { // 這個函式會在 utils.js 檔案中被呼叫 clearForm() { // 執行一些操作 },// 列印 utils.js 中的 description showMsg() { console.log(utils.description) } } } </script>
5. 其它思路
還有一種思路:
把一些屬性和方法掛載到 vue 例項原型上,自然也就可以在某個 js 檔案中拿到 vue 例項了。
以上就是如何在JS檔案中獲取Vue元件的詳細內容,更多關於在JS檔案中獲取Vue元件的資料請關注我們其它相關文章!