1

我正在尝试使用 vue apollo 进行本地状态管理,但即使在遵循文档之后我也没有得到任何结果。控制台中没有错误,所以我不确定出了什么问题。

这是我的设置:

// main.js file the initializing part

const client = new ApolloClient({
  link: ApolloLink.from([
    errorLink,
    authMiddleware,
    link,
  ]),
  cache,
  typeDefs,
  resolvers,
  connectToDevTools: true,
});
// resolvers file

import gql from 'graphql-tag';

import { todoItemsQuery } from './task.queries';

export const typeDefs = gql`
  type Item {
    id: ID!
    text: String!
    done: Boolean!
  }

  type Mutation {
    changeItem(id: ID!): Boolean
    deleteItem(id: ID!): Boolean
    addItem(text: String!): Item
  }
`;


export const resolvers = {
  Mutation: {
    checkItem: (_, { id }, { cache }) => {
      const data = cache.readQuery({ query: todoItemsQuery });

      console.log('data res', data);
      const currentItem = data.todoItems.find(item => item.id === id);
      currentItem.done = !currentItem.done;
      cache.writeQuery({ query: todoItemsQuery, data });
      return currentItem.done;
    },
  },
};

//queries file

import gql from 'graphql-tag';

export const todoItemsQuery = gql`
  {
    todoItems @client {
      id
      text
      done
    }
  }
`;

export const checkItemMutation = gql`
  mutation($id: ID!) {
    checkItem(id: $id) @client
  }
`;

// component where I call it

  apollo: {
    todoItems: {
      query: todoItemsQuery
    }
  },

    checkItem(id) {
      this.$apollo
        .mutate({
          mutation: checkItemMutation,
          variables: { id }
        })
        .then(({ data }) => {
          console.log("CACHE", data);
        });
    },

我得到空的 todoItems,没有错误。

请让我知道我错过了什么,我没有掌握一些我认为的概念,如果有办法将 vuex 与 apollo 一起使用,那么我也可以这样做。

4

1 回答 1

2

前言:我不是阿波罗专家,刚开始用。

以防万一,这些想法可能会对您有所帮助。如果他们不这样做,我很抱歉。

在 main.js 中:使用 Apollo Boost ( https://www.apollographql.com/docs/link/links/state/#with-apollo-boost )时,Apollo 文档提供了稍微不同的设置。以防万一,这就是我到目前为止设置实现的方式。

import VueApollo from 'vue-apollo'
import ApolloClient from 'apollo-boost';
import { InMemoryCache } from 'apollo-cache-inmemory';
const cache = new InMemoryCache();

Vue.use(VueApollo)
const apolloClient = new ApolloClient({
  //...whatever you may already have,
  clientState: {
    // "defaults" is your initial state - if empty, I think it might error out when your app launches but is not hydrated yet.
    defaults: {
      todoItems: [],
    }
    cache,
    typeDefs: {...yourTypeDefs},
    resolvers: {...yourResolvers},
  },
});
const apolloProvider = new VueApollo({
  defaultClient: apolloClient,
});

在您的 typeDefs 中:我看不到您的 todoItems 的查询类型:

type Query {
  todoItemsQuery: [Item]
}

在您的组件中:在我向 apollo 请求添加更新方法之前,我自己的实现无法正常工作:

apollo: {
  todoItems: {
    query: todoItemsQuery,
    update: data => data.todoItems
  }
},
于 2019-12-21T10:37:54.367 回答