javascript - 将 props 传递给 vue2 组件
问题描述
我想在 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");
主要内容.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>
解决方案
您设置应用程序的方式很尴尬。应用程序没有包装器。按照以下示例查看如何编排最终使您的组件具有所需的道具
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>
你可以在这里看到这个例子
推荐阅读
- javascript - JavaScript 注册验证问题
- python - psycopg2:TypeError:预期的字节或unicode字符串,得到了quoted_name
- swift - NSStatusItem 未显示在菜单栏中
- database - 无法启动 clickhouse 服务,../data/default/ 中的文件太多
- javascript - 替换动态表中的整个表行
- java - 服务器发送事件端点
- unity3d - Unity3D 相对于原始方向操纵对象方向
- sql - 运行总 sql SAP B1 - 找不到解决它的正确方法
- java - 在 Android Firebase 存储中上传文件后如何获取文件下载 URL?getDownloadUrl() 不工作
- javascript - SweetAlert2 蹩脚的文字