如何在辅助功能/ mixin中获取Vue模块
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在辅助功能/ mixin中获取Vue模块相关的知识,希望对你有一定的参考价值。
我在开发中使用Nuxt.js。
我使用cookie-universal-nuxt
在服务器端和客户端获取Cookie
modules:[
[.....] ,
[.....] ,
[.....] ,
['cookie-universal-nuxt', alias: 'myCookie' ],
]
而且我有一个辅助功能
// helper.js
const func =
getSomthingFromCookie(check)
return this.$myCookie.get('check') === check ? "something" : "else"
export default func
// another functions
const mixin =
methods:
getSomthingFromCookie(check)
return this.$myCookie.get('check') === check ? "something" : "else"
Vue.mixin(mixin)
// use this.getSomthingFromCookie outside
然后在商店或某些页面中使用它
// Page.vue or store.js
<div> helper.getSomthingFromCookie("test") </div>
..
..
..
..
..
import helper from '~/function/helper.js'
OR
const result = helper.getSomthingFromCookie("test")
但它返回:
Cannot read property 'get' of undefined
我认为是因为helper.js
无法访问vue实例,所以它无法获得this.$myCookie
。
我尝试过import Vue from 'vue'
和console.log(Vue)
但是登录终端就像
install: [Function] ,
install: [Function] ,
install: [Function] ,
install: [Function] ,
install: [Function] ,
install: [Function] ,
install: [Function] ,
install: [Function] ,
因此,我不确定能否在导入的$myCookie
中获得Vue
函数。
我知道我可以通过将getSomthingFromCookie.get('check')
移到外部并将其传递回给函数,例如:
getSomthingFromCookie(check,cookie) return cookie === check ? "something" : "else"
但这不是效率,需要更改许多代码。有更好的解决方案或建议吗?
我在开发中使用Nuxt.js。我使用cookie-universal-nuxt在服务器和客户端模块中获取cookie:[[.....],[.....],[.....],['cookie-universal-nuxt' ,别名:'...
答案
在helper.js
文件中,您无法使用vue
绑定访问this
实例。您必须显式导入Vue。
以上是关于如何在辅助功能/ mixin中获取Vue模块的主要内容,如果未能解决你的问题,请参考以下文章