javascript - Vue 组件找不到 Prop

标签 javascript webpack vue.js

这里是 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-showv-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/

相关文章:

typescript - 如何在 VS Code 的模板中为 vue Prop 启用 Typescript 类型和智能感知?

javascript - 为什么 ChartJs 不能在 IE 中运行

javascript - Readability 使用什么算法从 URL 中提取文本?

javascript - 当我在事件 "onbeforeunload"中进行异步 XMLHttpRequest 调用时,幕后会发生什么?

javascript - webpack如何压缩HTML代码中的链接CSS文件?

parsing - React - 模块解析失败

javascript - Webpack 5 - 未捕获的 ReferenceError : process is not defined

css - vuejs-datepicker 更改样式不起作用

javascript - 关于javascript字符串替换方法的问题

javascript - 如何使用 JS 将目标文件转换为 JSON