1

I want to create basic sample of single file component in vue. I have configured webpack to compile my code and it works fine. Now i want to pass props to component and i get error that props is undefined.

index file

    <head>
    <meta charset="UTF-8">
    <title>Vue Webpack Demo</title>
    <script type="text/javascript" src="/dist/vue.js"></script>
</head>
<body>
    <div id="mainContent">
        <main-content post-title="hello!"></main-content>
    </div>
</body>

<script src="/dist/index.js"></script>

index.js file

    import Vue from 'vue';
import MainContent from './views/main-content';

let MainComponent = Vue.extend(MainContent);

new MainComponent().$mount("#mainContent");

main-content.vue

<template src="./main-content.html"></template>
<style scoped lang="scss" src="./main-content.scss"></style>
<script>
    export default {
        name: "main-content",
        props: {
            postTitle:{
                type:String,
                required:true
            }
        },
        data: () => ({
            webpack: 'Powered by webpack!?',
            name:'name'
        }),
    }
</script>

1 Answer 1

1

The way you are setting up the application is awkward. There is no wrapper for the application. Following the following example to see how it can be orchestrated to finally have your component with the required prop

The index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>CodeSandbox Vue</title>
</head>
<body>
    <div id="app"></div>
    <!-- built files will be auto injected -->
</body>
</html>

The main.js where the vue application is created:

import Vue from "vue";
import App from "./App";

Vue.config.productionTip = false;

/* eslint-disable no-new */
new Vue({
  el: "#app",
  components: { App },
  template: "<App/>"
});

Now the App uses your component MainContent and passes the prop:

<template>
  <MainContent post-title="Hello!"/>
</template>

<script>
import MainContent from "./views/MainContent";

export default {
  name: "App",
  components: {
    MainContent
  }
};
</script>

Finally the component reads the prop:

<template>
  <div class="hello">
    post-title: {{ postTitle }}
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  props: {
    postTitle: {
      type: String,
      required: true
    }
  },
};
</script>

You can see this example working here

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

1 Comment

i followed this. medium.freecodecamp.org/….

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.