如何将Apollo与NativeScript vue集成?

时间:2020-02-22 07:26:43

标签: nativescript-vue vue-apollo

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

如何针对 nativescript-vue 进行修改?

vue-apollo软件包应该直接起作用吗? 甚至还有“带角的阿波罗”的例子。但不幸的是,我找不到有关nativescript-vue的说明。 @khalifa-gadit works fine具有本机脚本核心。但是它也可以与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
    });
  }
}

3 个答案:

答案 0 :(得分:1)

最近两个月我一直在将Vue-apollo与nativescript-vue一起使用。

使用JWT逐步安装阿波罗

  1. 使用vue-apollo手动安装 yarn add vue-apollo graphql apollo-boost
  2. 创建apollo.config.js文件
  3. 将阿波罗代码添加到您的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

答案 1 :(得分:1)

我用cem kaan的答案使它起作用-谢谢你。

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

旁注:我使用打字稿,所以如果您使用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条所述安装了插件,则可以直接尝试在querys.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. 尝试一下,希望您满意:)

请记住:路径可能还必须根据您的个人解决方案进行调整。

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

答案 2 :(得分:0)

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

UI插件的工作原理几乎与在Angular应用中使用NativeScript UI插件的工作原理相同。

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