【问题标题】:How to integrate Apollo with NativeScript vue?如何将 Apollo 与 NativeScript vue 集成?
【发布时间】:2020-06-06 13:15:31
【问题描述】:

如何从 Nativescript-vue 应用程序使用 GraphQL API?

nativescript-vue如何修改?

vue-apollo 包应该直接工作吗? 甚至还有一些“带角度的阿波罗”的例子。但不幸的是,我找不到 nativescript-vue 的说明。 @khalifa-gadit works fine 带有 nativescript 核心。但是它也适用于 nativescript-vue 吗?

有一个 complete implementation with angular

角度答案是:

import { NativeScriptModule } from 'nativescript-angular/nativescript.module';
import { NativeScriptHttpClientModule } from 'nativescript-angular/http-client';
import { ApolloModule, Apollo } from 'apollo-angular';
import { HttpLinkModule, HttpLink } from 'apollo-angular-link-http';

@NgModule({
  imports: [
    NativeScriptModule,
    NativeScriptHttpClientModule, // this provides HttpClient
    ApolloModule,
    HttpLinkModule
  ]
})
export class AppModule {
  constructor(
    apollo: Apollo,
    httpLink: HttpLink
  ) {
    // create Apollo
    apollo.create({
      link: httpLink.create({ uri }),
      // other options like cache
    });
  }
}

【问题讨论】:

  • 我之前使用过graphql没有问题,但不确定vue-apollo是否可以工作。你为什么不试一试,如果它不起作用,请发布错误/问题。

标签: nativescript-vue vue-apollo


【解决方案1】:

过去 2 个月我一直在使用 Vue-apollo 和 nativescript-vue。

使用 JWT 逐步安装 apollo

  1. 使用vue-apollo手动安装 yarn add vue-apollo graphql apollo-boost
  2. 创建apollo.config.jsfile
  3. 将 apollo 代码添加到您的 main.ts 文件中
import Vue from 'nativescript-vue'
import List from './components/List.vue'
import Login from './components/Login.vue'
import * as ApplicationSettings from "tns-core-modules/application-settings";
import VueDevtools from 'nativescript-vue-devtools'
import VueApollo from "vue-apollo";
import {
    ApolloClient,
    InMemoryCache,
    HttpLink,
    ApolloLink
} from "apollo-boost";
import { onError } from "apollo-link-error";
import { setContext } from "apollo-link-context";
/////////////// APOLLO
Vue.use(VueApollo);
const errorLink = onError(({ graphQLErrors }) => {
    if (graphQLErrors) graphQLErrors.map(({ message }) => console.log(message));
});
const httpLink = new HttpLink({
    uri: "https://polar-badlands-01357.herokuapp.com/graphql"
});
const authLink = setContext((_, { headers }) => {
    // get the authentication token from ApplicationSettings if it exists
    var tokenInAppSettings = ApplicationSettings.getString("token");
    // return the headers to the context so HTTP link can read them
    return {
        headers: {
            ...headers,
            authorization: tokenInAppSettings
                ? `Bearer ${tokenInAppSettings}`
                : null
        }
    };
});
export const apolloClient = new ApolloClient({
    link: ApolloLink.from([errorLink, authLink, httpLink]),
    cache: new InMemoryCache()
});

const apolloProvider = new VueApollo({
    defaultClient: apolloClient
});


if(TNS_ENV !== 'production') {
  Vue.use(VueDevtools)
}
import store from './store'

// Prints Vue logs when --env.production is *NOT* set while building
Vue.config.silent = true

new Vue({
  store,
  apolloProvider,
  render: h => h("frame", [h(ApplicationSettings.hasKey("token")? List : Login)])
}).$start()

如果有人感兴趣,请查看this complete Github repo 登录和变异示例。

对于经过完整测试的 nativescript-vue 插件数据库,请查看 plug-in page

【讨论】:

    【解决方案2】:

    我使用了 cem kaan 的答案来使它工作 - 所以谢谢你。

    但是,就我而言,它需要一些调整。为了让每个人都更容易,我将描述我到底做了什么(当然不包括我所有的固定错误:D),这需要一段时间。第1、5、6、7和10点主要基于cem自己的答案。由于包含阿波罗的方式发生了变化,其他的要么是新的,要么是经过大量调整的。

    旁注:我使用 typescript,所以如果您使用 javascript,您可能需要对其进行更多调整并使用 .js 文件而不是 .ts 文件。


    使用 GraphQL / Apollo 设置 NativeScript-vue

    1. 在您的项目中打开终端并通过输入这两个命令之一来安装 apollo-boost

      - yarn add vue-apollo apollo-boost graphql
      
      - npm i vue-apollo apollo-boost graphql
      
    2. (快速测试可选)在项目根目录中创建一个名为“.graphqlconfig”的新文件

    3. (快速测试可选)打开文件并粘贴此文件并根据您的个人端点进行调整

              {
                "name": "Your Schema",
                "schemaPath": "https://your.url.com/graphql",
                "extensions": {
                  "endpoints": {
                    "Default GraphQL Endpoint": {
                      "url": "https://your.url.com/graphql",
                      "headers": {
                        "user-agent": "TS GraphQL"
                      },
                      "introspect": false
                    }
                  }
                }
              }
    
    1. 我使用 vscode 并安装了插件 ApolloGraphQL 和 GraphQL 来简化使用 graphql。

    2. 创建一个名为“graphql”的新文件夹

    3. 在那里创建一个名为“queries.ts”的新文件

    4. 添加您的查询。该文件可能如下所示:

            import { gql } from "apollo-boost";
            export const GET_ITEMS = gql`
            query GetItemsQuery {
                getItems {
                  id, name, image
                }
            }
            `;
    
    1. 如果您按照 4 中所述安装了插件,您将能够直接尝试并执行 queries.ts 文件中的查询。

    2. 现在打开你的 main.ts 并添加以下行

            // [...] imagine here your other imports like nativescript-vue or devtools
        
            import ApolloClient from "apollo-boost"
            import VueApollo from "vue-apollo"
    
            const apolloProvider = new VueApollo({
              defaultClient: new ApolloClient({
                uri: "https://your.url.com/graphql"
              })
            })
    
            Vue.use(VueApollo)
    
            // [...] your other stuff like DevTool use or configuration
    
            new Vue({
              provide: apolloProvider.provide(),
              render: h => h('frame', [h(App)])
            }).$start()
    
    1. 在您的 *.vue 文件(我的路径:project/app/components)中包含查询,例如这个列表,首先在模板部分:
            <template>
        
               // [...] if this is not an imported component, here could be <Page> etc
        
               <GridLayout columns="*" rows="*,30">
                  <Label v-if="$apollo.loading" text="loading ...  " textWrap="true" row="0" col="0" />
                  <GridLayout v-else rows="*" columns="*" row="0" col="0">
                    <ListView for="item in getItems" row="0" col="0">
                      <v-template>
                        <Label :text="item.name"/>
                      </v-template>
                    </ListView>
                  </GridLayout>
                </GridLayout>
        
                // [...] possibly other stuff
        
            </template>
    
    1. 最后,在脚本部分,添加这个
            <script lang="ts">
            import Vue from "vue";
            import { gql } from "apollo-boost";
            import * as queries from "../../graphql/queries";
            import * as ApplicationSettings from "tns-core-modules/application-settings";
    
            export default {
              data() {
                return {
                  getItems: [],
                };
              },
              apollo: {
                getItems: {
                  // prefetch: true,
                  query: queries.GET_ITEMS,
                  update({ getItems }) {
                    return getItems;
                  }
                }
              }
            }
            </script>
    
    1. 尝试一下,希望您对它运行良好感到满意 :)

    请记住:路径也可能需要根据您的个人解决方案进行调整。

    我希望这对某人有帮助:)

    【讨论】:

      【解决方案3】:

      插件的工作方式与任何其他 NativeScript 应用程序一样,但您可能想知道 UI 插件如何与 Vue 配合使用。

      UI 插件的工作方式几乎与您在 Angular 应用中使用 NativeScript UI 插件的方式相同。

      根据document's 描述,对于我们必须注册的 UI 组件,插件可能开箱即用。我个人确实没有使用 vue-apollo,但我希望在 nativescript-vue 中工作。

      【讨论】:

      猜你喜欢
      • 2019-02-08
      • 2017-10-21
      • 1970-01-01
      • 2015-08-11
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2018-01-13
      相关资源
      最近更新 更多