服务器之家:专注于服务器技术及软件下载分享
分类导航

node.js|vue.js|jquery|angularjs|React|json|js教程|

服务器之家 - 编程语言 - JavaScript - 如何在JS文件中获取Vue组件

如何在JS文件中获取Vue组件

2021-09-28 12:26文渊 JavaScript

这篇文章主要介绍了如何在JS文件中获取Vue组件,帮助大家更好的理解和学习前端知识,感兴趣的朋友可以了解下

1. 背景

最近在写项目时候遇到这样一个需求:

  • 我封装了一个js文件 utils.js,然后在组件 my-component.vue 中引用了该js文件。
  • utils.js 文件中有一些函数,需要操作 my-component.vue 中的 datamethods

为了方便理解,上述 js 文件和组件名非实际工程中的名字,仅是示例。

2. 思路

通过调用函数把 组件实例 this 传递到 被应用的 js 文件 里。

3. 目录结构

?
1
2
3
4
5
6
7
8
9
src/
├── App.vue
├── assets
├── main.js
├── components
└── views
  └── demo
    ├── my-component.vue
    └── utils.js

4. 代码实现

utils.js 中定义一个变量和一个函数,该变量用于存放组件实例 this,该函数用于接收组件实例 this

utils.js

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// 用来存放调用此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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<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组件的资料请关注服务器之家其它相关文章!

原文链接:https://www.wenyuanblog.com/blogs/vue-get-the-component-instance-in-javascript-file.html

延伸 · 阅读

精彩推荐