vue
vue copied to clipboard
Support Array subclassing
Version
2.5.21
Reproduction link
https://codepen.io/AmrIKhudair/pen/NevxML
Steps to reproduce
1- create a class extending Array and add a custom method 2- instantiate a new instance of the class and add it to data 3- try to call the method on the instance in the template
What is expected?
The method is successfully executed
What is actually happening?
Error not a function
Vue 2 currently does not support Array subclassing (Vue 3 development branch already does). I will convert this into a feature request.
@AmrIKhudair I needed this as well and made it work in user-land. When Vue 3 arrives you can remove it.
export function makeReactive (obj) {
// eslint-disable-next-line no-proto
const proto = obj.__proto__
Object.defineProperty(obj, '__proto__', {
get () { return proto },
// eslint-disable-next-line no-proto
set (newValue) { proto.__proto__ = newValue }
})
}
import { makeReactive } from 'util'
export default class UserCollection extends Array {
constructor (...args) {
super(...args)
makeReactive(this)
}
}
@edcoreweb Thanks a lot
@AmrIKhudair I needed this as well and made it work in user-land. When Vue 3 arrives you can remove it.
export function makeReactive (obj) { // eslint-disable-next-line no-proto const proto = obj.__proto__ Object.defineProperty(obj, '__proto__', { get () { return proto }, // eslint-disable-next-line no-proto set (newValue) { proto.__proto__ = newValue } }) }
You saved my day in 2022