v-on:单击Nuxt组件中的永不触发按钮,因为中间件



我在其他地方的其他问题中看到过这个问题,但还没有看到解决方案。我正在尝试使用按钮制作一个简单的 GDPR cookie 通知,该通知在单击时关闭。我处于通用模式,这意味着mounted()不可用,所以我正在尝试通过 Vuex 设置 cookie。但是,我绑定到组件中的按钮的单击事件未触发。

编辑:在构建了我的应用程序的代码沙盒版本后,它正常工作,我浏览并破解了我的Nuxt应用程序,直到找到导致问题的原因。事实证明,这是我的中间件,更具体地说,是我使用fs-extra库读取 JSON 文件的事实。仍然不清楚为什么会发生这种情况,因此欢迎任何建议。下面的代码包括我的中间件。

components/CookieNotice.vue

<template>
<div v-if="cookie != true" class="cookie_notice_wrap">
<div class="cookie_notice">
<p class="notice_message">This site uses cookies for analytics purposes.</p>
<button @click.prevent="dismissNotification" class="notice_dismiss">Close</button>
</div></div>
</template>
<script>
import { mapGetters } from "vuex";
export default {
name: "CookieNotice",
methods: {
dismissNotification: function(e) {
console.log("we clicked?");
document.querySelector(".cookie_notice_wrap").classList.add("hidden_click");
this.store.dispatch("cookieStateChange", true);
}
},
computed: {
...mapGetters(["cookie"]),
}
}
</script>

来自store/index.js的操作

export const actions = {
async getPosts({ state, commit, dispatch }) {
if (state.posts.length) {
return
}
try {
await axios.get("/api/json-access");
}
catch (err) {
console.log(err);
}
},
nuxtServerInit({ state, commit, dispatch }, { req }) {
dispatch("getPosts");
const seen = this.$cookies.get("cookie_notice_seen");
if (!seen) {
dispatch("cookieStateChange", false);
}
},
cookieStateChange({state, commit, dispatch}, bool) {
// this does set the cookie correctly, unsure if it will work the same when bound to the button click
commit("updateCookie", bool);
this.$cookies.set("cookie_notice_seen", bool, {
path: "/",
maxAge: 60 * 60 * 24 * 7
});
}
}

~/middleware/api/json-access.js

const fse = require('fs-extra');
import axios from 'axios';
const storeLocation = "middleware/full_site.json";
export default async function({ store, route, redirect }) {
const exists = await fse.pathExists(storeLocation);
let posts;
if (!exists) {
await fse.ensureFile(storeLocation);
posts = await postsFromWP();
fse.writeJSON(storeLocation, posts);
}
else {
try {
posts = await fse.readJSON(storeLocation);
}
catch (err) {
console.log(err);
}
}
store.commit("updatePosts", posts);
}
async function postsFromWP() {
const url = ".../example/json/file.json";
const config = { headers: { "Accept": "application/json" }};
let posts = await axios.get(url, config);
posts = posts.data
.filter(el => el.status === "publish")
.map(({ id, slug, title, excerpt, date, tags, content }) => ({
id, slug, title, excerpt, date, tags, content
}));
return posts;
}

我之前通过routes -> middlewarenuxt.config.js中配置了中间件,但目前已将其设置为通过serverMiddleware进行测试。我还添加了触发获取帖子的操作,以防这也是其中的一部分。这绝对达到了我对Nuxt/Vue理解的极限 - 我不知道为什么会发生这种情况,所以任何智慧都非常感谢。

如果你最终处理类似的事情,fsfs-extra是你的罪魁祸首。您不能在客户端使用文件操作,这是这些中间件操作发生的时候(我认为(。只有当我删除中间件文件顶部的fs-extra导入时,cookie 通知才能完全工作。

最新更新