Giter VIP home page Giter VIP logo

nuxt-class-component's Introduction

Deprecated Repository

Please consider using nuxt-property-decorator instead.


Nuxt Class Component

ES and Typescript Class Components Decorators for Nuxt.js extending vue-class-component


Installation

npm install --save nuxt-class-component

# or

yarn add nuxt-class-component

Babel Instructions

npm install --save-dev babel-plugin-transform-decorators-legacy babel-plugin-transform-class-properties

# or

yarn add --dev babel-plugin-transform-decorators-legacy babel-plugin-transform-class-properties

Then you can configure Babel plugins on nuxt.config.js - Plugin order is important (see here):

module.exports = {
  build: {
    babel: {
      plugins: ['transform-decorators-legacy', 'transform-class-properties']
    }
  }
}

Typescript Instructions

You will need to enable [experimentalDecorators] on your Typescript compiler.(http://www.typescriptlang.org/docs/handbook/decorators.html).

  • Using Typescript Compiler argument --experimentalDecorators like this:
tsc --experimentalDecorators
  • Using tsconfig.json:
{
  "compilerOptions": {
    "experimentalDecorators": true,
    ...
  }
}

Usage

See vue-class-component, vuex-class documentation.

You can also see the official TypeScript examples of Nuxt.js.

Example

import Vue from 'vue'
import Component from 'nuxt-class-component'
import {
  State,
  Getter,
  Action,
  Mutation,
  namespace
} from 'vuex-class'

const Module = namespace('path/to/module')

@Component({
  props: {
    propMessage: String
  }
})
export class MyComp extends Vue {
  @State('foo') stateFoo
  @State(state => state.bar) stateBar
  @Getter('foo') getterFoo
  @Action('foo') actionFoo
  @Mutation('foo') mutationFoo
  @Module.Getter('foo') moduleGetterFoo
  @Module.Action('foo') moduleActionFoo

  // If the argument is omitted, use the property name
  // for each state/getter/action/mutation type
  @State foo
  @Getter bar
  @Action baz
  @Mutation qux

  // initial data
  msg = 123

  // use prop values for initial data
  helloMsg = 'Hello, ' + this.propMessage

  // lifecycle hooks
  created () {
    this.stateFoo // -> store.state.foo
    this.stateBar // -> store.state.bar
    this.getterFoo // -> store.getters.foo
    this.actionFoo({ value: true }) // -> store.dispatch('foo', { value: true })
    this.mutationFoo({ value: true }) // -> store.commit('foo', { value: true })
    this.moduleGetterFoo // -> store.getters['path/to/module/foo']
  }

  mounted () {
    this.greet()
  }

  fetch () {
    // fetch data
  }

  async asyncData () {
    // async fetching data
  }

  // computed
  get computedMsg () {
    return 'computed ' + this.msg
  }

  // method
  greet () {
    alert('greeting: ' + this.msg)
  }
}

License

MIT License - Copyright (c) Nuxt Community

nuxt-class-component's People

Contributors

alexjoverm avatar atinux avatar breakingrobot avatar clarkdo avatar johnlindquist avatar pawel-schmidt avatar renovate-bot avatar salihsagdilek avatar zl810881283 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

nuxt-class-component's Issues

Cannot resolve definitions for module nuxt-class-component

I'm using this template inside Webstorm and once I'm trying to import nuxt-class-component into my project I get a reference highlight in red giving me an error: Cannot resolve definitions for module nuxt-class-component although index.d.ts is present in the node_modules/nuxt-class-component/dist/ folder
image
When I try to fix it by importing a related @typed definition package
image
I get another error:
image
I tried to look for a related definition manually but seems like it doesn't exist in the @types repo.
Could someone help me fix this issue?

This question is available on Nuxt.js community (#c3)

Dynamic Import?

Any support for dynamic import (in case our module target is to esnext)?

This question is available on Nuxt.js community (#c5)

Purpose of package unclear

What are the goals?
What are the key differences from vue-class-component + vue-property-decorator?

This question is available on Nuxt.js community (#c4)

Adding `watchQuery` & `key` to @Component?

What problem does this feature solve?

Currently when using nuxt with ts - I'm unable to add watchQuery & key to my vue components.

Please see
https://github.com/nuxt/nuxt.js/blob/dev/examples/layout-transitions/pages/users.vue#L22-L25
and/or
https://nuxtjs.org/api/pages-watchquery

Further reference:
nuxt-community/nuxt-property-decorator#13

What does the proposed changes look like?

Adding the fields / ts definitinos?

This feature request is available on Nuxt community (#c8)

Deprecate this in favor of nuxt-property-decorator

With latest release of nuxt-property-decorator I don't seen any reason for using this library. Nuxt-property-decorator currently covers everything this library is offering and much more. So in order to avoid confusion, promote best practices and help to consolidate efforts, I suggest to deprecate this library and advice everyone to switch to nuxt-property-decorator. That should be really easy and pain free switch.

@Atinux @breakingrobot @clarkdo what do you think?

This question is available on Nuxt community (#c15)

[Question] what is difference from vue-class-component?

i'm making own Nuxt project with typescript.
and i got a problem that not triggering asynData methods, but when i
changing library vue-class-component to nuxt-class-compoent, it works.

but... why?
there is no source code related to asyncData (dist/index.js , dist/index.d.ts)

so i wonder that why is it works.


  • I found registerHooks API in lib directory.
    sorry :)
This question is available on Nuxt.js community (#c6)

layouts/default middleware is not working

// my default layout
@component({
components: {},
middleware: ['login']
})
export default class extends Vue {}

// .nuxt/server
if (layout.middleware) midd = midd.concat(layout.middleware)

I think it should be compile 'layout.options.middleware'

This question is available on Nuxt community (#c14)

Component config object can't be extended with `head` property

Version

v1.2.1

Reproduction link

https://github.com/nuxt-community/nuxt-class-component

Steps to reproduce

  • Create a component using @component decorator
  • Pass head property to a config object

What is expected ?

Title of the related page is changed

What is actually happening?

[tsl] ERROR in ...\nuxt-apollo-github\components\Inspirations.vue.ts(20,3)
      TS2345: Argument of type '{ head: { title: string; }; }' is not assignable to parameter of type 'VueClass<Vu
e>'.
  Object literal may only specify known properties, and 'head' does not exist in type 'VueClass<Vue>'.

Additional comments?

Same is happening with other custom properties. For example, if you try to use @nuxt/apollo module and it's apollo config property you will also get an error:

TS2345: Argument of type '{ apollo: { allInspirations: { prefetch: boolean; query: DocumentNode; }; }; head:
 { title: strin...' is not assignable to parameter of type 'VueClass<Vue>'.
  Object literal may only specify known properties, and 'apollo' does not exist in type 'VueClass<Vue>'.

I think any other custom property will also produce similar error.

This bug report is available on Nuxt community (#c9)

How to import Vue in all class based components

How can I prevent importing vue in every single component.

For instance in this component:

<template>
  <p>hello times: {{ helloTimes }}</p>
</template>

<script lang="ts">
import Vue from 'vue'
import Component from '../../../lib/index'
@Component
export default class Hello extends Vue {
  helloTimes: number = 0
  sayHello () {
    this.helloTimes++
  }
}
</script>

I want to automatically import vue in all classed based components.

Can't set middleware

I have the following in layout/default.vue:

<script>
export default {
  middleware: "connected"
}
</script>

connected is a middleware that checks a store state property and redirects if it is null. If I change to:

<script lang="ts">
import Component from "nuxt-class-component"
import Vue from "vue"

@Component({
  middleware: ["connected"]
})
export default class extends Vue {
}

</script>

Am I doing something wrong, or is this a bug in nuxt-class-component? It doesn't seem to matter whether middleware is a string or array.

Thanks.

This question is available on Nuxt.js community (#c1)

Babel installation instructions and config doesn't match

$ yarn add babel-plugin-syntax-flow babel-plugin-transform-flow-strip-types

Then:

module.exports = {
  build: {
    babel: {
      plugins: ['transform-decorators-legacy', 'transform-class-properties']
    },
...

The configured plugins don't match those installed in the previous step. Which plugins should I use?

Also, the README.md tells me to install the given plugins/config if I'm using Babel. Don't all Nuxt apps use Babel? And shouldn't the installed plugins use --dev?

Thanks.

This question is available on Nuxt.js community (#c2)

[RFC] Decorators for vue-apollo

What problem does this feature solve?

Right now, the smart query/subscrition of vue-apollo must be put into the class decorator of Component, and there're a lot of typing Catch-22s we had to turn off type checking temporarily to get it to stop redding our IDE.

Is there any decorators for vue-apollo? I believe there can also be some decorator sugars around it too, it would be much better.

What does the proposed changes look like?

We could have decorators like this:

@Component()
export default class HelloComponent extends Vue {
  world: string = "world"

  // Type I: Tag only (Can this be computed🤔)
  @SmartQuery(gql`query { hello }`)
  hello?: { data: hello }
  
  // Type II: With options
  @SmartQuery({
    query: gql`query { hello }`,
    fetchPolicy: 'cache-and-network'
  })
  hello2?: { data: hello }
  
  // Type III: Functional variable
  @SmartQuery(gql`query Hello($name: String!) {
    hello(name: $name)
  }`)
  hello3(name: string = this.world): any {
    return async (query: (variables?: any) => Promise<any>): Promise<any> => {
      return await query({ name })
    }
  }
  
  // Type III variant: Functional variable with options and default variable and scoped variable
  @SmartQuery({
    query: gql`query Hello($name: String!) {
      hello(name: $name)
    }`,
    /* !! This should be prohibited for all decorators !!
    variables: {
      message: 'Meow'
    },
    */
    skip: false
  })
  'hello3.5'(name: string = this.world): any {
    return async (query: (variables?: any) => Promise<any>): Promise<any> => {
      return await query({ name })
    }
  }
  
  // Type IV: Mutation
  @Mutation(gql`
    mutation {
      store(key: "123", value: "456") {
        key,
        value
      }
    }
  `)
  hello4(): any { // Sorry but I'm too lazy to type 😣
    return async (mutate: (variables?: any) => Promise<any>): Promise<void> => {
      const data = await mutate() // no variables supplied
      // ...update..., e.g. write to local storage etc.
    }
  }
  
  // Type V: Mutation with options and variables
  @SmartMutation({
    mutation: gql`
      mutation Store($key: String!, $value: String!) {
        store(key: $key, value: $value) {
          key,
          value
        }
      }
    `,
    optimisticResponse: {
      __typename: 'Mutation'
    }
  })
  hello5({ key, value }: { key: string, value: string }): any {
    return async (mutate: (variables?: any) => Promise<any>) => Promise<void> {
      const data = await mutate(variables) // with variables supplied
      // ...update..., e.g. write to local storage etc.
    }
  }
  
  // Type VI: Subscription
  @SmartSubscription(gql`subscription {
    hello
  }`)
  onHello({ hello }: { hello: string }): void { // corresponds to updateQuery
    // XXX: should this really be auto wrapped upon the true model? (see below Type VII)
    this.handleOnHello({ hello })
  }
  
  @Emit('hello')
  handleOnHello({ hello }: { hello: string }) {}
  
  // Type VII: Subscription with variables
  @SmartSubscription({
    document: gql`subscription Hello($name) {
      hello(name: $name)
    }`
  })
  onHello2(name: string): any {
    // XXX: Async iterator or observable?
    // Observable is more fitted to Vue philosophy,
    // but async iterator is much easier to implement
    return async (pullData: (variables?: any) => Promise<any>): Promise<void> => {
      // So we are not appending to local variables, instead we remap this into an event and do it there
      
      // XXX again: Some darker sides of async iterator
      // https://github.com/tc39/proposal-async-iteration/issues/126
      for await (const { data: { hello }, unsubscribe } of pullData({ name })) {
        this.handleOnHello({ hello }) 
        if (hello === 'world') await unsubscribe() // This is my proposed way to stop, but then it degenerates to observable...
      }
    }
  }
}

Consensus

This feature request is available on Nuxt community (#c10)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.