0

I'm using Nuxt and vue , so editing a single file component.

I a really struggling to set a variable and then use it in my template.

Eg. I have this in my script:

<script>

import headers from '~/components/headers.vue'
import { TweenMax, Back } from 'gsap'
import footers from '~/components/footer.vue'
import { headroom } from 'vue-headroom'

export default {
  data: () => ({
    intersectionOptions: {
      root: null,
      rootMargin: '0px 0px 0px 0px',
      thresholds: [0]
    } // https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API,
  }),
  created () {
    this.topPos = 140
  },
  mounted: function () {
    var main = document.getElementById('main')
    // onsole.log(this.$refs['main'][0])
    window.addEventListener('resize', () => {
      console.log('The offsetTop of Main is  ' + main.offsetTop)
      this.topPos = main.offsetTop

      document.getElementById('headroom').setAttribute(':offset', main.offsetTop)
      console.log('Tried' + main.offsetTop)
    })
  },
  methods: {
    onWaypoint ({ going, direction }) {
      // going: in, out
      // direction: top, right, bottom, left
      if (going === this.$waypointMap.GOING_IN) {
        console.log('Entering the div: ' + going + '.  Reduce Nav and transition menus and logo')
      }

      if (direction === this.$waypointMap.DIRECTION_TOP) {
        console.log('Moving towards ' + direction + '.  If up, we should transition in Nav.')
      }
    }
  },
  components: {
    headers,
    footers,
    headroom,
  }
}
</script>

Then I'm just trying to write out the variable in my template like so:

<p v-if="topPos">topPos... {{topPos}}</p>

No matter what I change, (even without the resize listener), I can't get the variable to update from the default '140'. Previously I set the default in "data{}" but still the same result.

How can I dynamically update variables in the template after rendering?

What glaring flaw am I missing?!

I have referred to VueJS: why is “this” undefined? but following that doesn't seem to fix it either.

Dom Huxley
  • 113
  • 2
  • 6
  • "data{}"? You are not showing that. Can you show more? – skribe Jan 24 '18 at 19:07
  • Thanks @skribe, I have shown the full contents of my 'script'. Previously I set 'topPos' in data but had exactly the same problem. – Dom Huxley Jan 24 '18 at 20:02
  • @thanksd - thanks for referring me to that one. Unfortunately that modification doesn't seem to work either. – Dom Huxley Jan 24 '18 at 20:02
  • You need to both set `topPos` as a property value in the object returned by the `data` method, and also make sure to not use an arrow function when defining your `mounted` hook. – thanksd Jan 24 '18 at 20:11
  • @thanksd. **Fixed** it for me! Just dodgy code then - as expected! Thanks very much. It was one attempt at fixing piled on top of another until I was completely lost. Cheers – Dom Huxley Jan 24 '18 at 22:20

0 Answers0