【问题标题】:Understanding props in vue.js了解 vue.js 中的 props
【发布时间】:2016-02-10 13:12:25
【问题描述】:

我正在阅读学习 vue.js 的指南,到了关于道具的部分,然后遇到了一个问题。

我知道子组件具有独立的范围,我们使用 props 配置将数据从父组件传递到它,但是当我尝试它时,我无法让它工作。

我有the example I'm working on up on js fiddle:

var vm = new Vue({
   el: '#app',
   // data from my parent that I want to pass to the child component
   data:{
       greeting: 'hi'
   },
   components:{
        'person-container':{

            // passing in the 'greeting' property from the parent to the child component
            props:['greeting'],

            // setting data locally for the child
            data: function (){
                return { name: 'Chris' };
            },

            // using both local and parent data in the child's template
            template: '<div> {{ greeting }}, {{ name }}</div>'
        }
   }
});

当我运行上面的代码时,我的输出只有:

,克里斯

子组件本地的数据渲染得很好,但是传入的父组件的数据要么没有通过,要么没有正确渲染。

我在 javascript 控制台中没有看到任何错误,并且模板正在呈现。

我是否误解了应该如何传递道具?

【问题讨论】:

    标签: javascript vue.js


    【解决方案1】:

    您必须像这样将值绑定到组件属性:

    <person-container v-bind:greeting="greeting"></person-container>
    

    Jsfiddle https://jsfiddle.net/y8b6xr67/

    在这里回答: Vue JS rc-1 Passing Data Through Props Not Working

    【讨论】:

      【解决方案2】:

      我已经更新了你的fiddle

      <person-container :greeting="greeting"></person-container>
      

      您需要在 html 组件上将 props 从父级传递给子级。

      【讨论】:

        【解决方案3】:

        您也可以将任何字符串传递给“greeting”,只需像普通的 html 属性一样设置它,而无需使用 v-bind 指令。

        <person-container greeting="hi"></person-container>
        

        也可以。请注意,您通过这种方式传递的任何内容都将被解释为纯字符串。

        <person-container greeting="2 + 2"></person-container>
        

        将产生“2 + 2,克里斯”。
        更多用户指南:https://vuejs.org/v2/guide/components.html#Props

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-06-08
          • 2017-08-14
          • 2019-10-30
          • 2019-02-22
          • 1970-01-01
          • 2017-09-15
          • 2019-05-19
          • 2021-05-22
          相关资源
          最近更新 更多