[英]Understanding props in vue.js
I'm working through the guide for learning vue.js, got to the section on props, and ran into a question.我正在阅读学习 vue.js 的指南,到了关于道具的部分,然后遇到了一个问题。
I understand that child components have isolated scops and we use the props configuration to pass data into it from the parent, but when I try it out I can't get it to work.我知道子组件具有独立的范围,我们使用 props 配置将数据从父组件传递给它,但是当我尝试它时,我无法让它工作。
I have the example I'm working on up on js fiddle :我有我正在研究 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>'
}
}
});
When I run the above code, my output is only:当我运行上面的代码时,我的输出只有:
, Chris
, 克里斯
The data local to the child component renders fine, but the passed in parent's data is either not coming through or is not properly rendering.子组件本地的数据渲染得很好,但是传入的父数据要么没有通过,要么没有正确渲染。
I don't see any errors in the javascript console and the template is rendering.我在 javascript 控制台中没有看到任何错误,并且模板正在呈现。
Am I misunderstanding how the props are supposed to be passed in?我是否误解了应该如何传递道具?
You have to bind the value to the component prop like this:您必须像这样将值绑定到组件道具:
<person-container v-bind:greeting="greeting"></person-container>
Jsfiddle https://jsfiddle.net/y8b6xr67/ jsfiddle https://jsfiddle.net/y8b6xr67/
Answered here: Vue JS rc-1 Passing Data Through Props Not Working在这里回答: Vue JS rc-1 通过道具传递数据不起作用
You can also pass any string to "greeting" by just setting it like normal html attribute, without using v-bind directive.您也可以将任何字符串传递给“greeting”,只需将其设置为普通的 html 属性,而无需使用 v-bind 指令。
<person-container greeting="hi"></person-container>
Will also work.也会起作用。 Note that anything you pass that way will be interpreted as plain string.
请注意,您通过这种方式传递的任何内容都将被解释为纯字符串。
<person-container greeting="2 + 2"></person-container>
Will result in "2 + 2, Chris".将导致“2 + 2,克里斯”。
More in user guide: https://v2.vuejs.org/v2/guide/components.html#Props更多用户指南: https ://v2.vuejs.org/v2/guide/components.html#Props
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.