vue使用文件中的变量
时间: 2023-11-27 11:03:12 浏览: 63
在 Vue 中使用文件中的变量可以通过以下方式:
1. 使用 import 导入变量:
在文件中定义变量或常量:
```javascript
// utils.js
export const API_BASE_URL = 'https://api.example.com'
```
在需要使用变量的组件中导入:
```javascript
// MyComponent.vue
import { API_BASE_URL } from '@/utils.js'
export default {
// ...
created() {
console.log(API_BASE_URL) // 输出 https://api.example.com
},
// ...
}
```
2. 在 Vue 实例中使用 Vue.observable 定义变量:
在 utils.js 中定义:
```javascript
// utils.js
import Vue from 'vue'
export const globalStore = Vue.observable({
API_BASE_URL: 'https://api.example.com',
})
```
在需要使用变量的组件中导入:
```javascript
// MyComponent.vue
import { globalStore } from '@/utils.js'
export default {
// ...
created() {
console.log(globalStore.API_BASE_URL) // 输出 https://api.example.com
},
// ...
}
```
这里的 @ 表示你的 src 目录,可以根据实际情况进行修改。
阅读全文
相关推荐
















