Git Product home page Git Product logo

vue-class-component's Introduction

[DEPRECATED] Vue Class Component

⚠️ Notice

This library is no longer actively maintained. It is no longer recommend to use Class-based components in Vue 3. The recommended way to use Vue 3 in large applications is Single-File Components, Composition API, and <script setup>. If you still want to use classes, check out the community-maintained project vue-facing-decorator.

Additionally, if you're interested in migrating out of class components, you might find the CLI tool vue-class-migrator helpful for the transition.


ECMAScript / TypeScript decorator for class-style Vue components.

npm Gitpod Ready-to-Code

Document

See https://class-component.vuejs.org

Please note, documentation for v8 is not ready yet. Check out the readme in the respective branch or see v8 proposals in the issue list

Online one-click setup for contributing

Contribute to Vue Class Component using a fully featured online development environment that will automatically: clone the repo, install the dependencies and start the docs web server and run yarn dev.

Open in Gitpod

Issue reporting / pull requests

See contribution guideline

License

MIT

vue-class-component's People

Contributors

304notmodified avatar ashtomgva avatar briangonzalez avatar brooooooklyn avatar christiankienle avatar decadef20 avatar dependabot[bot] avatar eddow avatar fachher avatar finico avatar haoqunjiang avatar herringtondarkholme avatar hjkcai avatar hmillison avatar imyth avatar kaorun343 avatar ktsn avatar kuitos avatar lmiller1990 avatar mikekidder avatar mirupal avatar nargonath avatar nikolarhristov avatar nisarhassan12 avatar rixlabs avatar sorayama avatar tryforceful avatar vip30 avatar yankeeinlondon avatar yyx990803 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  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

vue-class-component's Issues

Define mixin global does not work

Hi all,

I tried creating a mixin in the Vue-Class-Component format like below:

import Vue from 'vue'
import Component from 'vue-class-component'

@Component()
export default class HelloMixins extends Vue{
  helloMixinsData = 'Hello mixin class component!'
  created() {
    console.log('created: ', this.helloMixinsData)
  }
}

And I try to use it in two ways:

Option 1: Register and use that mixin locally:

@Component({
    // Register mixin locally
    mixins:[HelloMixins]
})
export default class Parent extends Vue {
...
}
<template>
<div>{{helloMixinsData}}</div>
</template>

With this option, it works fine.

Option 2: Register and use that mixin globally:

// Register mixin globally
Vue.mixin(HelloMixins)
...
@Component({})
export default class Parent extends Vue {
...
}
<template>
<div>{{helloMixinsData}}</div>
</template>

With this option, it throws an error:

Property or method "helloMixinsData" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option.

Does anyone point out to me what the problem is?

Can I customize the parent class

hi, 小尤
vue-class-component is extends the Vue prototype , can I customize the parent class ?

class Base { getOption(){ console.log("this is father option") } ... someMethods() }

and element class extends Base some methods

class Element extends Base { ready(){ this.getOption(); } }

Exapmles of usage of Mapped actions inside the calls

Hi,
Would it be possible to provide some examples on how to use mapped actions and mutations inside the class? I read the #56 it shows how to map them but does not show how to use this mapped mutations and actions. If you do something like this

@Component({
  methods: {
    ...mapActions('
      'doSomething'
    )
  }
})

export default class MyComp extends Vue {
    test() {
        this.doSomething('test')
    }
}

It will not have an access to doSomething method inside the class.

hot reload?

Are there any plans to support hot-reloading of templates like for example vueify does?

constructor构造器在class中为什么不执行呢?

请教一下,我在某个class继承Vue或不继承Vue,然后调用其构造函数(constructor),为什么构造函数都不会执行呢?

import Vue from 'vue'
import Component from 'vue-class-component'
import tpl from './about.tpl.html' //html-loader

@Component({
    template: tpl
})
class About extends Vue{

    constructor(props) {
        super(props);
        console.log(props);
    }

    ready() {
        //console.log(this);
    }
}

console.log(new About() instanceof Vue); // console log: true

export default About;

还有就是上面的class在superProto instanceof Vue的执行始终是false,这和new About() instanceof Vue的执行结果相反,这是为什么呢?(:зゝ∠)

var superProto = Object.getPrototypeOf(Component.prototype)
  var Super = superProto instanceof Vue /* console log: false */
    ? superProto.constructor
    : Vue
  return Super.extend(options)

Class properties not being added to data

I'm currently experiencing an issue where the class properties are not being added to data.

Webpack loader:

{
    test: /\.js$/,
    exclude: /(node_modules|bower_components)/,
    loader: 'babel',
    query: {
        presets: ['es2015'],
        plugins: [
            'transform-decorators-legacy',
            'transform-class-properties',
        ]
    }
},

Using the linked @prop decorators does work.

import { Component, prop, watch } from 'vue-property-decorator';

@Component({
    template: `
    <div>
      <input v-model="msg">
      <p>prop: {{propMessage}}</p>
      <p>msg: {{msg}}</p>
      <p>helloMsg: {{helloMsg}}</p>
      <p>computed msg: {{computedMsg}}</p>
      <button type="button" @click="greet">Greet</button>
    </div>
  `,
})
export class Diet {
    // initial data
    @prop({
        type: Number,
        default: 123
    })
    msg;

    @prop(String)
    propMessage;

    helloMsg = 'Hello';

    // // lifecycle hook
    // mounted () {
    //     this.greet()
    // }

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

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

helloMsg will not be available here.

[Question] Same component same instance :S

Probably we are doing something wrong but when we use the same component multiple times, sames that vue is using the same instances:

@Component({
    template: require('./menu.component.html'),
})
export class Bymenu extends Vue {
    public email: string = '';
    private userService: UserService;

    created(UserService) {
        this.userService = UserService;
    }

    mounted() {
        this.email = (this.userService.get()).email;
    }
}

parent:

<div class="by-app-wrapper">
    <bymenu></bymenu>
    <bymenu></bymenu>
</div>

console:
image

Problem?
Both times is executing mounted method but only the first is updating the email value:
image

Example with imported components?

Is there an example for including an imported Vue component?
E.g.
I'm trying to get from:

import FormSignUps from './FormSignUps.vue'
export default {
  data: () => ({
    scrollY: 0,
  }),
  components: {
    'FormSignUps': FormSignUps,
  },
}

to???

import Vue from 'vue'
import Component from 'vue-class-component'
import FormSignUps from './FormSignUps.vue'

@Component(props: {??})
export default class App extends Vue {
  scrollY = 0
  components: {
    'FormSignUps': FormSignUps,
  }
}

how to use this with vue-router

i use this with vue-router, then ...
Module build failed: Error: Could not find file: 'E:\testproject\src\pages\act\App.vue'

Public static class properties/methods

Hello! Thank you for your job. Is it possible to use typescript static properties? For example getter/setter:

public static get StaticProp()

I've tried it, but after decoration I've lost static props.

observe router lifecycle hooks

It would be nice to observe beforeRouteEnter and beforeRouteLeave as lifecycle hooks. Should they be added to the internal hooks list?

They seem as common, if not more common than some of the other hooks, especially for confirming page exit

How to use it with vue 1.0.26 ?

Recently I was doing a Typescript project with vue 1.0.26, with the increase in the size of the project, we feel the need to import the library, but did not seem to find support vue 1.0 version.

ViewRouter conflict @Component to break scoped css

I am finding a weird situation with after upgrading npm packages, where my 'scoped' css is not being correctly 'scoped'. The dom elements do not get id'd.

I find that it is when i export a @component, and also have Vue.use(VueRouter) in the app.

So, somehow ViewRouter is conflicting with @component to break css scoping.

To replicate, simply install VueRouter in a test base project that exports using:

...
<script>
import Component from 'vue-class-component'

@Component export default class Login {
  name = 'hello'
  msg = 'Welcome to Your Vue.js App'
}
</script>
...
import Vue from 'vue'
import App from './App'
import VueRouter from 'vue-router'

Vue.use(VueRouter)

/* eslint-disable no-new */
new Vue({
  el: '#app',
  template: '<App/>',
  components: { App }
})

"vue": "^2.0.1",
"vue-class-component": "^4.3.1",
"vue-router": "^2.0.3"

Using props in initial data?

From the example in README there's:

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

If I copy the full example into a component and use it, helloMsg is always undefined (even when the prop is set to a string). Should this be the case*? It works in other methods and such, but not in initial data.

*The wording in that comment makes it seem like this should not be undefined. :)

Examples with gulp and browserify?

Do you have examples working with TypeScript + Gulp? I have always errors like prototype is undefined Object vue is null, etc.

Some tests:
app.ts

import Vue from 'vue'
import App from './app.component'

export default new Vue({
  el: '.js-app',
  render: h => h(App, {
    props: { propMessage: 'World' }
  })
});

app.component.ts

import Vue from 'vue'

export default class App extends Vue {
  propMessage: string
  msg = 123
  helloMsg = 'Hello, ' + this.propMessage

  mounted () {
    this.greet()
  }

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

  greet () {
    alert('greeting: ' + this.msg)
  }
}
import Vue from 'vue'
import Component from 'vue-class-component'

@Component({
  template: '<button @click="onClick">Click!</button>'
})
export default class MyComponent extends Vue {
  message = 'Hello!'

  onClick (): void {
    window.alert(this.message)
  }
}
Uncaught TypeError: Object prototype may only be an Object or null: undefined
    at setPrototypeOf (<anonymous>)
    at __extends (app.js:8)
    at app.js:16
    at Object.1.vue (app.js:37)
    at s (app.js:1)
    at app.js:1
    at Object.2../app.component (app.js:45)
    at s (app.js:1)
    at e (app.js:1)
    at app.js:1

Having any type in Component

@Component({
  template: require('./grid.html'),
  name: 'grid',
  props: {
    results: Array<any>
  }
})

Currently, having type of Array<any> is giving error. Can we have any type for props ?

Babel vs Typescript

Just wondering what the thoughts are re choosing between Babel and Typescript for a Vue + TS project?

migration path for vue-typescript

Hi, I've been using the vue-typescript project, which is excellent, BUT, doesn't support Vue 2.0.
https://github.com/itsFrank/vue-typescript
The issue I filed on 5 weeks ago has had no response.

So, am wondering if you'd consider adding some of the features of that project here.
For example:

@Watch - a watcher on computed values and/or properties
@Prop ({required: true}) - easier way to specify properties.

This would make it easier to transition to your project.

Doesn't work with Nuxt

I use Nuxt and I try to use class-component, I installed the plugin:

{
  "plugins": [
    "transform-decorators-legacy",
    "transform-class-properties"
  ]
}

also I tried add in inside nuxt.config

build: {
      vendor: ['vue-class-component'],
      babel: {
        plugins: [
          'transform-decorators-legacy',
          'transform-class-properties'
        ]
      }
    }

but nothing works, What I do incorrect?

how to use with vuex

How can i use mapActions, or mapGetters with using classes?

in vuex they use:

computed: {
...mapState('foo', {
// state is the state of the foo/ module instead of root
bar: state => state.bar
}
},
methods: {
...mapActions('foo', [
// map this.doSomething() to this.$store.dispatch('foo/doSomething')
'doSomething'
])
}

Using props

Description for vue-class-component is unclear, at least to me, for using props in typescript class if I define e.g.:
@component({
props: {
id: Number,
name: String
}
})

How Can I use prop value in class? Do I define them as class property again?

class Test extends Vue {
id: number;
name: string;

get NameId() {
return this.name + this.id;
}
}

Please advise, thanks!

Create decorators for directives not working

Hi all,
I tried to create decorator for directives as following:

export function Directive(path, hook, options = {}) {
   const { deep = false, immediate = false } = options

   return createDecorator((componentOptions, handler) => {
     if (typeof componentOptions.directives !== 'object') {
       componentOptions.directives = Object.create(null)
     }
     componentOptions.directives[path] = {[hook]:{ handler, deep, immediate }}
     console.log('DIREC-DECO: path', path)
     console.log('DIREC-DECO: hook', hook)
     console.log('DIREC-DECO: ', componentOptions)
   })
 }

....

@Directive('focus', 'inserted')
   focusInserted(el){
     el.focus()
   }

And when used that decorator as following:

<input v-focus>

But I got an error:

Uncaught TypeError: fn is not a function
at callHook$1 (eval at (app.js:741), :5234:5)
at callInsert (eval at (app.js:741), :5177:9)
at wrappedHook (eval at (app.js:741), :1709:10)
at Object.invoker [as insert] (eval at (app.js:741), :1656:16)
at invokeInsertHook (eval at (app.js:741), :4960:28)
at Vue$3.patch [as patch] (eval at (app.js:741), :5124:5)
at Vue$3.Vue._update (eval at (app.js:741), :2035:19)
at Vue$3.updateComponent (eval at (app.js:741), :2158:10)
at Watcher.get (eval at (app.js:741), :2469:25)
at new Watcher (eval at (app.js:741), :2452:12)

I don't understanding the cause of this error, Please help me for solve this issue.

extends option in vue-class-component

hi all,
I tried using extends option in vue-class-component

// file test.vue
<template>
  <div>display data tin extend {{msg}}</div>
</template>

<script>
var Child = {
  data: function(){
      return {
          msg: "Child component"
      }
  }
}
@Component({
  props: {
    extends : Child
  }
})
export default class MyComponent extends Vue {
}
</script>

Question: I didn't see that it work , how to using https://vuejs.org/v2/api/#extends option in vue-class-component.

vue-class-component breaks correct functioning of Vue.Extend

First of all, thanks a lot for vue-class-component. It's indispensable for serious vuejs work with ts.

I'm starting from the startup sample of vue with the webpack template, which has an Hello Component with a unit test on this Hello component. So just the standard stuff. I'm using typescript.

Inside the standard unit test the vm is setup as follows

import Hello from '../../../src/components/Hello.vue';
const Constructor = Vue.extend(Hello);
const vm = new Constructor().$mount();

When I transform now the Hello.vue component in such a way I use vue-class-component, the test will BREAK.

<template>
  <div class="hello">
    <h1>{{msg}}</h1>
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
@Component({
   name: 'hello'
})
export default class Hello extends Vue {
  msg: string = 'some text here';
}
</script>

I can only get the test working again by changing the way Vue.extend is used:

const Constructor = Vue.extend({ template: '<div><hello></hello></div>', components: { 'hello': Hello } });
    const vm = new Constructor().$mount();

I'm trying to understand what's going on here.
Thanks a lot for shedding a light on this.

Testing

Wondering what and end-to-end test setup with Vue and Typescript would look like, using, say:

  • Nightwatch.js
  • Jest with snapshots

thanks
David

Typescript Issue

I am trying to run your example with with Typescript 1.8 but am having issues. I get the error while compiling:

Offending Line: 
  get computedMsg () {
    return 'computed ' + this.msg
  }
[ts] Property 'msg' does not exist on type 'Greeter'.
any

I remove the offending line, it compile fine, and I use chrome dev tools to see if msg exists on the this object. It does, your decorator worked just fine! So for some reason its like the typescript compiler doesnt understand that the msg proeprty will be created by the decorator and stops compilation (stops, this is not a warning).

Anyways, I cloned the repo and ran your example (it uses babel, not typescript) and had no issues with your class-component decorator.

Just wondering if I am doing something wrong, any typescript example with this decorator?

Cannot find name 'Vue'

I've just started a typescript/electron app, and after getting the basics down with normal component files, I tried switching to vue-class-component.

After installing and changing one component over to this format and compiling with tsc, I'm getting:

> tsc --p tsconfig.json
node_modules/vue-class-component/lib/declarations.d.ts(3,13): error TS2304: Cannot find name 'Vue'.
node_modules/vue-class-component/lib/index.d.ts(4,38): error TS2304: Cannot find name 'Vue'.
node_modules/vue-class-component/lib/index.d.ts(4,52): error TS2503: Cannot find namespace 'Vue'.
node_modules/vue-class-component/lib/util.d.ts(3,60): error TS2503: Cannot find namespace 'Vue'.
node_modules/vue-class-component/lib/util.d.ts(3,119): error TS2304: Cannot find name 'Vue'.
node_modules/vue-class-component/lib/util.d.ts(4,60): error TS2503: Cannot find namespace 'Vue'.
node_modules/vue-class-component/lib/util.d.ts(4,134): error TS2304: Cannot find name 'Vue'.

Here's my tsconfig.json:

{
	"compilerOptions": {
		"target": "es6",
		"moduleResolution": "node",
		"lib": [
			"dom",
			"es2016"
		],
		"rootDir": "src/",
		"outDir": "dist/",
		"module": "commonjs",
		"allowJs": true,
		"removeComments": true,
		"emitDecoratorMetadata": true,
		"experimentalDecorators": true
	}
}

package.json:

"devDependencies": {
        "copyfiles": "^1.0.0",
        "electron": "^1.4.12",
        "node-sass": "^4.0.0",
        "typescript": "^2.1.4",
        "vue": "^2.1.6",
        "vue-class-component": "^4.4.0"
}

src/package.json

"dependencies": {
	"@types/electron": "^1.4.29",
	"@types/node": "^6.0.52",
	"@types/vue": "^1.0.31"
}

I'm roughly following the project structures from https://github.com/wspl/electron-boilerplate-typescript-vue and https://github.com/bradstewart/electron-boilerplate-vue, hence the two package.json's.

Any input would be appreciated, I really want to use this plugin.

Styles?

Hello,

I really like this approach, but I miss styling. How to embed scoped styles in a component? Similiar to *.vue's <style scoped> tags ?

Thanks,
Howe

error TS2339: Property 'propMessage' does not exist on type 'App'.

Execute README example code, and get this error message.

It seems cannot understand variables defined in Component props section.

error TS2339: Property 'propMessage' does not exist on type 'App'.

Develop Environment:

  • Typescript: 2.1.4
  • Vue: 2.1.6
  • vue-class-component 4.3.1

Hot Module Reload for Components

First I want to thank you for this component that bring typescript and VueJS together.

This reunion comes at a cost since HMR (Hot Module Reload) is not working anymore.
Do you think it's possible to enable HMR when a class is decorated ?
Or should we implement HMR ourself when importing a class using this decorator ?

Silent errors in hooks

If an error occurs in hook (beforeRouteEnter), it fails silently. There's no log in the console, the router just fail to change with no more info.

Maybe it's a vue-router issue, I did not test with Vanilla JS.

I can't load another component `B` when the component `A` that use `B` loaded with this loader

backdrop.vue:

<template>
    <div :class="{
        'cover-screen': mode === 'screen',
        'cover-container': mode === 'container',
        'hidden': !data.value
    }" @click="data.value = false"></div>
</template>

<script>
    import Vue from 'vue';

    export default {
        props: {
            showWhen: {
                requires: true
            },
            mode: {
                'default': 'screen'
            }
        }
    }
</script>

Vue component that uses this loader:

<script>
    import Vue from 'vue';
    import Component from 'vue-class-component';
    import Bindable from './reusable/class/Bindable';
    import Backdrop from './reusable/backdrop.vue';
    import HTMLView from './templates/my-vue-cpn.tpl.html';

    @HTMLView
    @Component({
        components: {
            'backdrop': Backdrop
        }
    })
    export default class MyVueCpn extends Vue {
        ...
    }
</script>

Error messages:

[Vue warn]: Error in render function: 
(found in <Backdrop> at /some-folder/components/reusable/backdrop.vue)
warn @ vue.js:569
handleError @ vue.js:1450
Vue._render @ vue.js:3521
updateComponent @ vue.js:2100
get @ vue.js:2417
Watcher @ vue.js:2400
mountComponent @ vue.js:2114
Vue$3.$mount @ vue.js:7153
Vue$3.$mount @ vue.js:9154
init @ vue.js:3006
createComponent @ vue.js:4523
createElm @ vue.js:4466
createChildren @ vue.js:4591
createElm @ vue.js:4499
patch @ vue.js:4923
Vue._update @ vue.js:1994
updateComponent @ vue.js:2104
get @ vue.js:2417
Watcher @ vue.js:2400
mountComponent @ vue.js:2114
Vue$3.$mount @ vue.js:7153
Vue$3.$mount @ vue.js:9154
init @ vue.js:3006
createComponent @ vue.js:4523
createElm @ vue.js:4466
createChildren @ vue.js:4591
createElm @ vue.js:4499
createChildren @ vue.js:4591
createElm @ vue.js:4499
createChildren @ vue.js:4591
createElm @ vue.js:4499
createChildren @ vue.js:4591
createElm @ vue.js:4499
patch @ vue.js:4959
Vue._update @ vue.js:1994
updateComponent @ vue.js:2104
get @ vue.js:2417
Watcher @ vue.js:2400
mountComponent @ vue.js:2114
Vue$3.$mount @ vue.js:7153
Vue$3.$mount @ vue.js:9154
Vue._init @ vue.js:3652
Vue$3 @ vue.js:3733
(anonymous) @ catalog.js:18
(anonymous) @ build.js?__CACHEBUSTER__:58796
__webpack_require__ @ bootstrap b0d827d…:19
(anonymous) @ main.js:8
__webpack_require__ @ bootstrap b0d827d…:19
(anonymous) @ bootstrap b0d827d…:39
(anonymous) @ bootstrap b0d827d…:39
vue.js:1454TypeError: Cannot read property 'value' of undefined
    at Proxy.render (backdrop.vue?cf34:6)
    at VueComponent.Vue._render (vue.js:3519)
    at VueComponent.updateComponent (vue.js:2100)
    at Watcher.get (vue.js:2417)
    at new Watcher (vue.js:2400)
    at mountComponent (vue.js:2114)
    at VueComponent.Vue$3.$mount (vue.js:7153)
    at VueComponent.Vue$3.$mount (vue.js:9154)
    at init (vue.js:3006)
    at createComponent (vue.js:4523)

Am I doing it wrong or it is a bug for this loader? I need to extract HTML and convert Backdrop.vue to use this loader too?

Do not use extends

Hello.

In owr projects we use a lot of extends classes hierachies. If you design the class style for vue like extends Vue. We can't use our currect oop code. It is better to design the framework compatibily with implements.

Inferno and React have the same problem.

In real projects the focus is on the technical (formal) requirements and should leave the inheritance path free.

Why is 'vue-property-decorator' library not a part of vue-class-component?

To write vue components using classes, we need to be able to do things such as 'watch' values. It makes sense to me that this should be a part of the same repo?

Looking at vue-property-decorator, since it can export Componenti guess we have this functionality already, just under a different (less appropriate library name)

import { Component, prop, watch } from 'vue-property-decorator';

should be

import { Component, prop, watch } from 'vue-class-component';

or

import { prop, watch }, Component from 'vue-class-component';

How to structure Vue (TypeScript) components?

How are you using this plugin? I'm currently using this on a .ts file, my components directory are composed by:

  • .ts file for vue-class-component specification;
  • .html file for template - using require('./') on .ts file;
  • .scss file for stylesheet - using css-modules to import them on .ts file;

I couldn't figure out how to use this on a .vue single file. What are the other options here?

Thanks

Mutations of data in arrow functions declared as instance variables are ignored

In the following example, mutations of this.width and this.height in onResize do not actually change the size of the div element.

<template>
<div v-bind:style="{ background: 'red', width: width + 'px', height: height + 'px' }"></div>
</template>

<script>
import Vue from 'vue'
import Component from 'vue-class-component'

@Component
export default class FollowWindowSize extends Vue {
  width = window.innerWidth
  height = window.innerHeight
  onResize = () => {
    this.width = window.innerWidth
    this.height = window.innerHeight
  }

  mounted() {
    window.addEventListener('resize', this.onResize)
  }

  destroyed() {
    window.removeEventListener('resize', this.onResize)
  }
}
</script>

This is because, after the babel transpilation, onResize is declared inside constructor, which is executed before the wrapping of the data with getters and setters by Vue.js take place, and therefore mutations of data in onResize are not handled by these setters.
I confirmed that this is also the case when TypeScript is used.

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.