0

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.

1
  • 5
    What you're describing is a store that holds the data and can be referenced throughout your application. Have no fear vuex is here Commented Feb 22, 2018 at 19:16

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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://v2.vuejs.org/v2/guide/mixins.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.