【问题标题】:Vue prop passed to a component is not defined传递给组件的 Vue prop 未定义
【发布时间】:2018-07-09 11:59:28
【问题描述】:

鉴于以下代码,我得到“ReferenceError: myvar is not defined”。这里有什么明显的错误吗?如果我在没有 jQuery 包装器的情况下运行它,它不会再给我错误,但它仍然没有按预期显示“是”。

https://jsfiddle.net/p14tvhap/

<div id="app">
  <my-component myvar="1" inline-component>
    <h1 v-if="myvar == 1">Yes</h1>
    <h1 v-if="myvar == 2">No</h1>
  </my-component>
</div>

$(function() {

  Vue.component('my-component', {
    props: ['myvar']
  })

  app = new Vue({
    el: '#app',
  });
})

【问题讨论】:

  • 你想做什么?为什么不在主实例中设置myvar?当您执行v-if="myvar==1 时,它会在主实例中查找myvar
  • 会有多个组件都使用相同的变量名作为配置变量。每个组件对该配置变量都有不同的值。我试图以某种方式在组件的“开始”处初始化变量的值。
  • 在这种情况下,我会创建一个类似的对象。 { myvars: { component1var: 1, component2var: 2 ... }} 然后将其传递给组件。但是,您将失去始终使用myvar 的便利。
  • 如何在每个组件vuejs.org/v2/guide/components.html#data-Must-Be-a-Function的“数据”中定义它?
  • 朝着正确的方向前进,谢谢。我在 标签上使用了“inline-component”而不是“inline-template”。这就是问题所在! vuejs.org/v2/guide/components.html#Inline-Templates

标签: javascript vue.js vuejs2 vue-component


【解决方案1】:

我必须将“inline-component”更改为“inline-template”,然后它才起作用。

【讨论】:

    【解决方案2】:

    vue props 在 : 之前传递

      <my-component :myvar="1" inline-component>
    

    【讨论】:

    • 因为我认为您使用 inline-template 只是为了演示目的。在组件中定义模板。
    • 这不一定是真的。添加:dynamically binds props,但不需要标记为prop
    • 其实是的,但为什么不总是使用动态道具
    猜你喜欢
    • 2020-02-07
    • 2018-09-14
    • 2018-11-16
    • 1970-01-01
    • 2021-11-02
    • 2019-06-20
    • 2021-10-21
    • 2017-08-19
    • 2020-10-11
    相关资源
    最近更新 更多