Vuejs Es6类反应性

时间:2018-04-01 17:39:52

标签: javascript vue.js ecmascript-6 es6-class vue-reactivity

我试图在与es6类关联的vuejs中拥有一个计算属性。 我的Vue实例看起来像这样:

...
props: ['customClass'],
computed: {
    localClass: {
         get() {
             return this.customClass
         },
         set (value) {
             console.log("changed")
         }
     }
 }
 ...

我的班级看起来像这样

class CustomClass {
    constructor () {
        this.selected = false
    }
}

如果我尝试做类似的事情:

this.localClass.selected = true

但从未调用过setter,因为反应已经丢失,我不明白为什么。

我也试试:

Vue.set(this.localClass, 'selected', true)

我将customClass作为道具传递,但即使在组件中直接创建新实例也不会改变结果。

在vuejs docs中,我不记得有一节谈论es6课程中的反应性问题,所以我想知道是否有人知道为什么以及如何让我的课程被动反应。

提前致谢

1 个答案:

答案 0 :(得分:0)

当您分配给该属性时,会触发计算属性的setter(例如myComputedProperty)(例如this.myComputedProperty = {something: 'else'}

您可能正在寻找的是watcher, more specifically, a watcher with deep: true,例如:

watch: {
  localClass: {
    deep: true,
    handler() {
      out.innerHTML += "watched!";
    }
  }
},

下面的演示。



class CustomClass {
  constructor() {
    this.selected = false
  }
}
Vue.component('custom', {
  template: '#custom',
  props: ['customClass'],
  computed: {
    localClass: {
      get() {
        return this.customClass
      },
      set(value) {
        out.innerHTML += "changed!\n";
      }
    }
  },
  watch: {
    localClass: {
      deep: true,
      handler() {
        out.innerHTML += "watched!\n";
      }
    }
  },
  methods: {
    assignToSelected() {
      this.localClass.selected = true
    },
    assignToLocalClass() {
      this.localClass = {
        selected: true
      }
    }
  }
});
new Vue({
  el: '#app',
  data: {
    test: new CustomClass()
  },
})

#out { background: black; color: gray; }
span { font-size: x-small; font-family: verdana }

<script src="https://unpkg.com/vue"></script>

<template id="custom">
  <div>
    {{ localClass }}
    <br>
    <button @click="assignToSelected">assignToSelected</button>
    <span>Note: will trigger "watched!" just once, because, since the value is hardcoded in the method (see code) subsequent clicks won't modify the value.</span>
    <br><br>
    <button @click="assignToLocalClass">assignToLocalClass</button>
    <span>Note: assignToLocalClass() will trigger the computed setter, but wont trigger the watcher because the computed setter currently sets nothing, so nothing changed for the watcher to trigger.</span>
  </div>
</template>

<div id="app">
  <custom :custom-class="test"></custom>
</div>

<pre id="out"></pre>
&#13;
&#13;
&#13;