gregdevs
gregdevs

Reputation: 713

vuejs - Changing a computed property via a method

I am trying to adjust a computed property within a vue component inside a method. When this property changes I am trying to show/hide a div. Currently when I perform the click event, I am seeing the correct boolean log under the set function, but not seeing any change to the showBanner prop.

Here's where I'm at.

HTML

<template>
  <div v-if="someConfig.displayBanner && showBanner" class="bn-banner">
    {{showBanner}}
  </div>
</template>


<script>
  import { mapActions, mapState } from 'vuex';

  export default{

    name: "myComponentShell",

    computed: {
      ...mapState('utilitiesStore', [
        'someConfig'
        ]),

        styleObject () {
          return {
            background: this.someConfig.colorHex
          }
        },

    showBanner:{

      get () {
        return (this.someConfig.text === localStorage.getItem("gma_alerts_hide")) ? false : true
      },

      set (value) {
        console.log(value)
        return value
      }
    }


    },

    methods: {
      ...mapActions('utilitiesStore', [
          'getJSON'
        ]),

        closeBreaking () {
          localStorage.setItem("someData", this.someConfig.text)
          this.showBanner = false;
        }
    },

  }

</script>

Upvotes: 4

Views: 24315

Answers (3)

Eduardo Aguad
Eduardo Aguad

Reputation: 841

That's because you're returning a value instead of assigning a value in your set method of showBanner computed property.

Try something like

set (value) {
  this.someConfig.text = value; // I assign a value so get() method will trigger
}

Keep in mind that set method must modify something in order to see changes in showBanner

https://v2.vuejs.org/v2/guide/computed.html#Computed-Setter

Upvotes: -1

ElsaKarami
ElsaKarami

Reputation: 646

you can use && operator in your code to fixed "text is undefined" error

(this.someConfig && this.someConfig.text)

Inside this code:

data () {
return {
    showBanner: (this.someConfig.text === localStorage.getItem("gma_alerts_hide")) ? false : true
}}

Upvotes: 0

Ohgodwhy
Ohgodwhy

Reputation: 50798

showBanner is not truly a computed property, it is simply a variable who's state is initialized from a ternary. Therefore you should just declare it as a data property.

data () {
    return {
        showBanner: (this.someConfig.text === localStorage.getItem("gma_alerts_hide")) ? false : true
    }

}

Then this.showBanner = false; makes sense.

Edit Updated data declaration because you're using single file components.

Upvotes: -1

Related Questions