1
votes

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?

1

1 Answers

2
votes

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>