Vue2 使用 apollo 将 vuex 存储数据传递给指令

问题描述

我在我的商店中定义了这个页脚:

export default new Vuex.Store({
  state: {
    pages: [],footer: null,loading: false,},mutations: {
    setPages: (state,payload) => (state.pages = payload),setFooter: (state,payload) => (state.footer = payload),setLoading: (state,payload) => (state.loading = payload),actions: {
    getPages: ({ commit }) => {
      commit("setLoading",true);
      apolloClient
        .query({ query: pageCollection })
        .then(({ data }) => {
          commit("setPages",data.pageCollection.items);
          commit("setLoading",false);
        })
        .catch((error) => {
          console.log(error);
          commit("setLoading",false);
        });
    },getFooter: ({ commit }) => {
      apolloClient
        .query({ query: footerCollection })
        .then(({ data }) => {
          console.log(data.footerCollection.items[0]);
          commit("setFooter",data.footerCollection.items[0]);
        })
        .catch((error) => console.log(error));
    },getters: {
    pages: (state) => state.pages,footer: (state) => state.footer,loading: (state) => state.loading,modules: {},});

在我的页脚中,我这样做:

import {
  computed,defineComponent,getCurrentInstance,} from "@vue/composition-api";

import { content } from "@/directives";

export default defineComponent({
  name: "TheFooter",directives: {
    content,setup() {
    const instance = getCurrentInstance();
    const store = instance.proxy.$store;
    store.dispatch("getFooter");

    const footer = computed(() => store.getters.footer);

    return { footer };
  },});

如您所见,我将页脚传递给组件。从这里我可以执行类似 {{ footer }} 的操作来查看 json 响应。但我想将页脚(部分)传递给指令。 我试过这样做:

<div v-content="footer" v-if="footer"></div>

在我的指令中,我控制台记录页脚,如下所示:

import { DirectiveBinding } from "vue/types/options";

export const content = {
  bind(el: HTMLElement,binding: DirectiveBinding): void {
    const { value } = binding;
    const openMarks = {
      bold: true,italic: true,underline: true,};
    console.log(value);
    // const html = parseHtmlString(value,openMarks);
    // console.log(html);
    // el.innerHTML = html;
  },};

但我得到的是一个 observable 而不是一个对象。

enter image description here

如何解开 observable 以便解析它?

解决方法

首先,您希望在 console.log() 中看到您的页脚。一些浏览器具有更好的功能,能够读取您的 observable 对象,但简单的方法是将其包装和解包为 JSON,因此:

console.log(JSON.parse(JSON.stringify(value)));

其次,您试图将页脚作为指令输出,这很奇怪,而不是我会采用的方法。相反,如果您将页脚设为自己的组件会怎样?我认为它可以工作并且更干净,并且可能最终为您提供更多功能。

<my-app-footer />
<template>
  <div v-if="footer" v-html="footer">
  </div>
</template>

<script>
import { mapGetters } from "vuex";

export default {
  computed {
    ...mapGetters(["footer"]);
  }
}
</script>