【问题标题】:How to access vuex store from `index.html`?如何从`index.html`访问vuex存储?
【发布时间】:2021-07-22 21:08:15
【问题描述】:

我必须在我的 vue Web 应用程序中嵌入一些脚本标签。我不确定在哪里添加它,但我选择将它们添加到index.html#app div 所在的位置。

index.html 下方,我必须嵌入至少 3 或 4 个脚本标签,并创建一些更改语言的 cookie,设置用户的偏好,以便跟踪或不跟踪他们。为此,我需要访问 vuex 商店。

如果我尝试访问store 形式的index.html 的属性,例如this.$store.getters.getActiveLanguage;,则会出错。

Uncaught TypeError: Cannot read property 'getters' of undefined

听起来我无法从这里访问商店。我该如何解决,有人可以帮忙吗?提前谢谢你

编辑:index.html 中的完整代码示例

    <!-- Cookie Consent by https://www.FreePrivacyPolicy.com -->
<script type="text/javascript" src="//www.freeprivacypolicy.com/public/cookie-consent/3.1.0/cookie-consent.js"></script>
<script type="text/javascript">
  document.addEventListener("DOMContentLoaded", function() {
    cookieconsent.run({ notice_banner_type: "interstitial", consent_type: "express", palette: "dark", language: "en" });
  });
</script>

<!-- easy -->
<!-- const language = .localSorage.getItem("language"); -->
<script type="text/plain" cookie-consent="functionality">
  document.cookie = "functionalityCookie=en";
  this.$store.getters.getActiveLanguage; 
</script>

<script type="text/plain" cookie-consent="tracking">
  document.cookie = "trackingCookie=true";
</script>

<script type="text/plain" cookie-consent="strictly-necessary">
  document.cookie = "strictlyNecessaryCookie=true";
</script>

<!-- end of easy-->

<noscript
  >Cookie Consent by <a href="https://www.FreePrivacyPolicy.com/free-cookie-consent/" rel="nofollow noopener">FreePrivacyPolicy.com</a></noscript
>

【问题讨论】:

  • 如果没有更多示例代码,很难说问题出在哪里。但是this.$store 只能在 Vue 内部工作,例如在组件内部。在其他任何地方它都不会简单地工作。
  • 我刚刚添加了完整的代码,我还指出了我想如何访问商店,但听起来我无法访问它。您认为最好的解决方案是什么?

标签: javascript cookies vuex vuejs3


【解决方案1】:

在您的情况下,this 等于 window

我要做的是在mounted 上运行cookieconsent.run,您可以在其中设置用户的当前语言

new Vue({
  el: '#app',
  store: store,
  mounted () {
    const language = this.$store.getters.getActiveLanguage;
    cookieconsent.run({ 
      notice_banner_type: "interstitial", 
      consent_type: "express", 
      palette: "dark", 
      language: language 
    });
  }
})

【讨论】:

  • 我已经在 #app 中挂载了另一个 vue 实例,不会产生问题
  • 不,我不是这个意思,我的意思是你应该把它添加到你现有的 Vue 保险中
猜你喜欢
  • 2018-09-29
  • 2018-07-06
  • 2018-11-10
  • 1970-01-01
  • 2018-12-08
  • 2021-06-17
  • 2020-08-17
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多