1, the computed

  • Computed, though it looks like a method, actually computes attributes, so you use it the same way you use attributes, without parentheses.
  • Computed data is displayed dynamically based on the dependent data, and the computed results are cached, and the computed values are recalculated only after the dependent data has changed.

The sample

new Vue({
  data: {
    users: {
      id: 1.name: "Zhang".phone: "123456"}},computed: {
    _user: {
      get() {
        return this.users.name + ":" + this.users.phone;
      },
      set(value) {
        this.users.name = value; }}},template: ` < div > {{_user}} < button @ click = "name = 'bill'" > elegantly-named setName < / button > < / div > `
}).$mount("#app");
Copy the code

Note:

In the example above, you could write {{this.users.name + “:” + this.users.phone}} directly in the template string. The expressions in the template are very handy, but they are designed for simple operations. Putting too much logic into a template can make it too heavy and difficult to maintain.

2, watch

  • Watch is a listening callback to data data. When the dependent data changes, the callback is executed, which is asynchronous and will be passed innewValandoldVal.
  • There are two options,immediateTo set whether to execute on the first render,deepUsed to set changes in the internal properties of the object to listen for

The sample

new Vue({
  data() {
    return {
      n: 0.history: [].isUndo: false
    };
  },
  methods: {
    add() {
      this.n += 1;
    },
    undo() {
      const last = this.history.pop();
      this.isUndo = true;
      this.n = last.from; // Trigger an asynchronous update of watch
      this.$nextTick(() = > {
        // setTimeout needs to be set after the previous update
        this.isUndo = false;
      }, 0); }},watch: {
    n(newN, oldN) {
      // this. IsUndo is executed when this. IsUndo is false
      if (!this.isUndo) this.history.push({ from: oldN, to: newN }); }},template: ` < div > {{n}} < hr > < button @ click = 'add' > + 1 < / button > < button @ click = 'undo' > cancel < / button > < hr > {{history}} < / div > `
}).$mount("#app");
Copy the code

Compute properties are more appropriate in most cases, but sometimes you need a custom listener. This approach is most useful when asynchronous or expensive operations need to be performed when data changes.