将道具传递给vue2组件

时间:2018-11-05 08:39:08

标签: javascript vuejs2

我想在vue中创建单个文件组件的基本示例。我已经配置了webpack来编译我的代码,并且效果很好。现在我想将道具传递给组件,但出现错误,提示道具未定义。

索引文件

    <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文件

    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 个答案:

答案 0 :(得分:1)

设置应用程序的方式很尴尬。该应用程序没有包装。通过下面的示例,可以了解如何最终使组件具有所需的道具

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>

创建vue应用程序的main.js:

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

Vue.config.productionTip = false;

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

现在,该应用使用您的组件MainContent并传递prop

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

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

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

最后,组件读取道具:

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

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

您可以看到此示例工作here