在vue2项目中全局引入并使用js
1.在main.js中引入
import Vue from 'vue'
import api from 'util/API/api.js'
//方法一
Vue.prototype.$api = api
//方法二
window.api=api
2.在页面中直接使用,例如:
<script>
export default {
name: 'home',
created() {
//方法一的使用方法
this.$api.info()
//方法二的使用方法
api.info()
}
}
</script>
其中在uniapp中全局引入和使用js的方法如同vue2的方法一
在vue3项目中全局引入并使用js
1.在main.js中引入
const app = createApp(App)
import axios from './util/axios'
app.config.globalProperties.$axios = axios;
2.在页面中使用,例如:
<script>
import{onMounted,getCurrentInstance} from 'vue'
export default {
name: 'home',
setup() {
// vue3中取消了this的概念,可用getCurrentInstance来获取上下文,这里的proxy相当于this
const { proxy } = getCurrentInstance()
onMounted(()=>{
//需要先借助getCurrentInstance来获取上下文
proxy.$axios.get('/index-infos')
})
}
}
</script>