簡體   English   中英

了解 vue.js 中的 props

[英]Understanding props in vue.js

我正在閱讀學習 vue.js 的指南,到了關於道具的部分,然后遇到了一個問題。

我知道子組件具有獨立的范圍,我們使用 props 配置將數據從父組件傳遞給它,但是當我嘗試它時,我無法讓它工作。

我有我正在研究 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 控制台中沒有看到任何錯誤,並且模板正在呈現。

我是否誤解了應該如何傳遞道具?

您必須像這樣將值綁定到組件道具:

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

jsfiddle https://jsfiddle.net/y8b6xr67/

在這里回答: Vue JS rc-1 通過道具傳遞數據不起作用

我已經更新了你的小提琴

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

您需要在 html 組件上將 props 從父級傳遞給子級。

您也可以將任何字符串傳遞給“greeting”,只需將其設置為普通的 html 屬性,而無需使用 v-bind 指令。

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

也會起作用。 請注意,您通過這種方式傳遞的任何內容都將被解釋為純字符串。

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

將導致“2 + 2,克里斯”。
更多用戶指南: https ://v2.vuejs.org/v2/guide/components.html#Props

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM