Vue mutable

Proxies your props into mutable local state.

Version: 1.1.1 Updated: 02/17/2020

By: sagalbot License: MIT

Install

npm i vue-mutable
yarn add vue-mutable

Repository: https://github.com/sagalbot/vue-mutable

CDNs

bundle.run: https://bundle.run/vue-mutable

jsDelivr: https://cdn.jsdelivr.net/npm/vue-mutable

unpkg: https://unpkg.com/vue-mutable

Vue Mutable

Proxy your props into mutable local state.

Install

npm i --save vue-mutable
# or
yarn add vue-mutable
// Installs a global mixin
import { VueMutable } from 'vue-mutable';
Vue.use(VueMutable);

// Or, use the mixin directly in your component
import { mutableProps } from 'vue-mutable';

export default {
  mixins: [mutableProps]
  ...
}

Why

If you need to modify a prop in a components local state, you need to do a few things:

  1. Define a data property
  2. Set the data property value to the prop value in a lifecycle hook
  3. Set a watcher for the prop so that if the parent updates the value, the internal value is synced
{
  props: {
    options: {
      default: []
    }
  },
  data() {
    return {
      _options: []
    }
  },
  created() {
    this.$data._options = this.options;
  },
  watch: {
    options(new, old) {
      this.$data._options = new;
    }
  }
}

Vue Mutable simplifies the process for you. Flag any prop as mutable and it will be accessible internally as a data property.

{
  props: {
    options: {
      default: [],
+     mutable: true
    }
  },
}

This will allow you to use this.$data._options in your component.

Categories: Vue js