如何在JS⽂件中获取Vue组件
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)
}
}
}
图片编辑器app</script>
5. 其它思路
还有⼀种思路:
把⼀些属性和⽅法挂载到 vue 实例原型上,⾃然也就可以在某个 js ⽂件中拿到 vue 实例了。
以上就是如何在JS⽂件中获取Vue组件的详细内容,更多关于在JS⽂件中获取Vue组件的资料请关注其它相关⽂章!