Vue-next: Basic store pattern example doesn't work

Created on 10 Jan 2020  路  4Comments  路  Source: vuejs/vue-next

Version

3.0.0-alpha.1

Reproduction link

https://jsfiddle.net/fva48tsr/

Steps to reproduce

I tried out the basic store pattern example from the docs, but it doesn't ever update.

<template>
  <div>{{ sharedState.counter }}</div>
</template>

<script>
var store = {
  state: {
    counter: 0
  },
  increment: function() {
    this.state.counter  ;
  }
};

export default {
  data: function() {
    return {
      sharedState: store.state
    };
  },
  mounted: function() {
    setInterval(() => {
      store.increment();
    }, 1000);
  }
}
</script>

What is expected?

The counter goes up

What is actually happening?

The counter doesn't change

Most helpful comment

You should use ref or reactive api to make the data is observed in v3.

All 4 comments

You should use ref or reactive api to make the data is observed in v3.

this.state.counter ++

The issue is that your this in increment is refering to the unproxied state object so vue does not track changes made through it.

Working version here

In Vue 2, plain objects are converted in-place to become reactive. But in Vue 3, due to the use of proxy-based reactivity system, the original object and the reactive proxy have different identities.

So:

import { reactive } from 'vue'

const a = { count: 0 }
const proxyA = reactive(a)

console.log(proxyA === a) // false

So in Vue 3, if you want to define a standalone reactive object, the recommended approach is to always explicitly wrap it with reactive at creation (and essentially never use the original object):

const store = reactive({
  state: {
    counter: 0
  },
  increment: function() {
    this.state.counter  ;
  }
})
Was this page helpful?
0 / 5 - 0 ratings

Related issues

anandkumarram picture anandkumarram  路  4Comments

Jexordexan picture Jexordexan  路  4Comments

doman412 picture doman412  路  3Comments

HakamFostok picture HakamFostok  路  3Comments

cexbrayat picture cexbrayat  路  4Comments