0
votes

I'm really confused with how data works in single file components for VueJS. Within the file, say test.vue, as I understand, you would write out a script something like this:

export default {
  name: 'Testapp',
  data () {
    return {
      msg: 'sample message'
    }
  }
}

then elsewhere, say in a file called vuescript.js I would put something like following in and call it from an html file:

import Vue from 'vue' import VApp from './test.vue'

var vueApp = new Vue({
  el: '#app',
  render: h => h(VApp)
})

Now how do I access that template object's data? What I'd like is to have code elsewhere that fetches data from a server and can be shared across multiple components, so I'd have a portion of data that is common across and updates from a single repository, but also I'd be able to have unshared data residing within a component for certain things like settings and other meta data.

BLUF: I'm kind of stuck after looking around a bit on how data is accessed / is handled within Vue single file components.

2
What you're describing is a store that holds the data and can be referenced throughout your application. Have no fear vuex is hereOhgodwhy

2 Answers

2
votes

Data inside components should only be accessed outside of themselves in 2 ways. Either an event propagated the data upwards to a parent which can then decide if it needs to be passed to another component as a prop. Or it is stored in Vuex and accessed through getters and mutations.

Links

Component Props

Events

Vuex Example

1
votes

If you want your data property to be shared by multiple components, you can use mixins.

Mixins are a flexible way to distribute reusable functionalities for Vue components. A mixin object can contain any component options. When a component uses a mixin, all options in the mixin will be “mixed” into the component’s own options.

https://vuejs.org/v2/guide/mixins.html