首页 > 解决方案 > Vue 组件的 prop 未定义(致命错误)

问题描述

我是 vue.js 框架的新手。我正在研究它并尝试在我的爱好项目中使用它。我尝试使用道具创建这个组件(组件未完成):

Vue.component('ingredient_select', {
    props: [name, selectedValue, text, ajaxUrl],
    template: `
        <select name="{{ name }}">
            <option value="{{ selectedValue }}">{{ text }}</option>
        </select>
    `
});
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>
  </head>
  <body></body>
</html>

Vue.js 抛出错误:“ReferenceError: selectedValue is not defined”。

我从我的 vue 模板中删除了组件的标签,但仍然抛出了同样的错误。我已经阅读了有关组件道具的手册:https ://vuejs.org/v2/guide/components-props.html ,但我仍然不知道我错过了什么以及我做错了什么。你可以帮帮我吗?我希望我犯了非常愚蠢的错误:)

PS:我的 IDE (PHP Storm) 没有显示任何 JavaScript 语法错误。

标签: javascriptvue.jsvue-component

解决方案


您应该将 props 定义为字符串数组,而不是变量:

props: ['selectedValue', 'text', 'ajaxUrl']

此外'name',对于道具来说,这并不是一个好名字。

Vue.component('ingredient_select', {
    props: ['sname', 'selectedValue', 'text', 'ajaxUrl'],
    template: `
        <select name="{{ sname }}">
            <option value="{{ selectedValue }}">{{ text }}</option>
        </select>
    `
});
<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/vue@2.5.22/dist/vue.js"></script>
  </head>
  <body></body>
</html>


推荐阅读