[Vuejs]-Splice array type prop in Vue component

0👍

splice won’t trigger the set on a computed. The easiest thing to do is to do an assignment to itself afterwards.

this.customBenefitsObj = this.customBenefitsObj;

See the demo below, which only writes "Test" once.

Vue.config.productionTip = false;
Vue.config.devtools = false;

new Vue({
  el: "#app",
  computed: {
    test: {
      get() {
        return [1, 2, 3, 4, 5];
      },
      set(v) {
        console.log("Test");
      }
    }

  },
  mounted() {
    this.test.splice(0, 1);
    this.test = this.test;
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app"></div>

0👍

By calling splice you modify a content of customBenefitsObj but not an array itself. If you do something like this:

this.customBenefitsObj = []

then customBenefitsObj’s set will be called and emit as well.

Also it’s not recommended to mutate a prop. You should emit a modified copy of an array and overwrite it in a parent component OR emit a remove operation and an element to remove (an actual remove also should be in a parent component).

Leave a comment