2

I've been working with Vue for sometime, but I've never really tried working with Single File Components alongside webpack. Here's the problem I'm having. I have 2 files: main.js (which contains the Vue root instance) and App.vue (which is a single file component. The code in each file goes as thus:

main.js:

import Vue from 'vue'
import App from './App.vue'

new Vue({
  el: '#app',
  components: { App, },
  data(){
    return {
        greeting: "Hello World!",
     }
  },
  render: h => h(App),

});

App.vue:

<template>
  <div id="app">
    {{greeting}}
  </div>
</template>

<script>
export default {
  name: 'App',
  
  }
  
 </script>

Please note that I'm using webpack, and the main.js file is meant to be an entry point. The code is bundled to a file called bundle.js.

Now, my problem is that, when the template in App.vue renders, it doesn't show "Hello Word", which is the value of {{greeting}}. I expect that data passed from the root Vue instance in main.js should be available to the App.vue component.

The {{greeting}} isn't evaluated when I put it in my index.html file, which links to bundle.js (the bundled version of main.js)

index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Nothing</title>
    <script src="/dist/build.js"></script>
  </head>
  <body>
    <div id="app"></div>
      {{greeting}}

  </body>
</html>

Does this mean that data in the root vue instance isn't available anywhere? What should I do?

0

1 Answer 1

3

The greeting needs to be in your component's data. This has nothing to do with SFC (Single File Components), it's just the way Vue's templates work: they read from the component's data.

So what you need to do is move the data to the appropriate component, which is tied with the template where you're trying to use.

<template>
  <div id="app">
    {{ greeting }}
  </div>
</template>

<script>
export default {
  name: 'App',
  data () {
    return { greeting: 'Hello World!', }
  },
}  
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, I knew this. I was only given an example of the problem I'm facing. There are some kind of data I need to store in the root instance so that I can make it available to many components all at once. How would I do this? It's not working.
You cannot randomly access from the parent component. Pass it as a prop to the child components as usual. Alternatively, you can access the this.$root. Again, none of these has to do with the fact that you're working with SFC. I suggest going over Vue's official tutorials.

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.