如何在辅助功能/ 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模块的主要内容,如果未能解决你的问题,请参考以下文章

vuex辅助函数以及模块化

从辅助域调用主应用域中的方法并获取值

VUE-X 辅助函数用法及分模块使用vuex

如何在 Rails 中正确使用控制器辅助模块,以及如何连接这些辅助模块?

如何通过辅助功能 API 获取当前选定文本的全局屏幕坐标。

如何在 Rails 模块中定义辅助方法?