这里是 Vue 的基本实现作为测试运行,我在将数据分解为组件时遇到了一些问题。这是 HTML:
<body>
<header id="main-header">
<custom-header></custom-header>
</header>
</body>
我正在实例化一个 Vue 实例并将其绑定(bind)到 #main-header:
import CustomHeader from '../header.vue';
chx = {
dates: { dateFormatted:"2016-01-01"},
title: "Hello World",
settingsVisible: false
}
const header = new Vue({
el: '#main-header',
data: chx,
components: {
'custom-header': CustomHeader
},
methods: {
run: function() {
console.log('run');
},
print: function() {
window.print()
},
save: function() {
console.log('save');
}
}
});
以及导入的模板:
<template>
<div>
<div class="header-menu">
<img class="logo" src="images/logo.png">
</div>
<i v-on:click="run" id="run" class="fa fa-3x fa-play-circle run-icon no-print" aria-hidden="true"></i>
<div class="header-menu">
<h1 id="date-range-label"><span v-show="dates.startFormatted">{{dates.startFormatted}} - {{dates.endFormatted}}</span></h1>
<i v-on:click="settingsVisible = !settingsVisible" id="settings" class="fa fa-2x fa-cog settings-icon no-print"></i>
</div>
</div>
</template>
<script>
export default {
props: ['title', 'dates']
}
</script>
我最大的问题是我的模板无法从我创建的 chx
对象中找到任何数据。我收到错误“TypeError:无法读取未定义的属性“startFormatted””
。我假设我可能必须使用 bind
但我不确定它如何与 v-show
和 v-on
结合使用。
最佳答案
对于第一部分,您需要在 header.vue
中定义一个 prop像这样的组件:
props: {
'propname': { type: Object }
}
然后传递chx
您在父组件中创建的对象:
<custom-header :propname="chx"></custom-header>
现在您可以在子组件中访问父组件的数据,如下所示:
{{ propname.dates.startFormatted }}
对于问题的第二部分,您需要触发一个事件来通知父组件更新 settingsVisible
。您可以这样解决这个问题:
<i v-on:click="toggleSettings()" id="settings" class="..."></i>
//
//
methods: {
toggleSettings() { this.$emit('toggle'); }
}
并在父组件中监听 toggle
事件:
<custom-header :propname="chx" v-on:toggle="chx.settingsVisible = !chxsettingsVisible"></custom-header>
您可以通过阅读 this document 获取更多信息页。
祝你编码愉快!
关于javascript - Vue 组件找不到 Prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45087667/