本文实例为大家解析了vue中Props的属性,供大家参考,具体内容如下
使用 Props 传递数据
组件实例的作用域是孤立的。这意味着不能并且不应该在子组件的模板内直接引用父组件的数据。可以使用 props 把数据传给子组件。
“prop” 是组件数据的一个字段,期望从父组件传下来。子组件需要显式地用 props 选项 声明 props:
Vue.component('child', { // 声明 props props: ['msg'], // prop 可以用在模板内 // 可以用 `this.msg` 设置 template: '<span>{{ msg }}</span>'})
然后向它传入一个普通字符串:
<child msg="hello!"></child>
举例
错误写法:
<!DOCTYPE html><html lang="en"><head> <script type="text/javascript" src="./vue.js"></script> <meta charset="UTF-8"> <title>vue.js</title></head><body><pre> //使用 props 传输资料予子组件 //props , data 重复名称会出现错误</pre><div id="app1"> <child mssage="hello!"></child></div><script> Vue.config.debug = true; Vue.component('child', { // declare the props props: ['msg','nihao','nisha'], // the prop can be used inside templates, and will also // be set as `this.msg` template: '<span>{{ msg }}{{nihao}}{{nisha}}</span>', data: function() { return { mssage: 'boy' } } }); var vm = new Vue({ el: '#app1' })</script></body></html>
正确写法:
<!DOCTYPE html><html lang="en"><head> <script type="text/javascript" src="./vue.js"></script> <meta charset="UTF-8"> <title>vue.js</title></head><body><pre> //使用 props 传输资料予子组件 //props , data 重复名称会出现错误</pre><div id="app1"> <child mssage="hello!"></child></div><script> Vue.config.debug = true; Vue.component('child', { // declare the props props: ['msg','nihao','nisha'], // the prop can be used inside templates, and will also // be set as `this.msg` template: '<span>{{ msg }}{{nihao}}{{nisha}}</span>' }); var vm = new Vue({ el: '#app1' })</script></body></html>
props 传入多个数据(顺序问题)
第一种:
HTML
<div id="app1"><child msg="hello!"></child><child nihao="hello1!"></child><child nisha="hello2!"></child></div>
JS
Vue.config.debug = true; Vue.component('child', { // declare the props props: ['msg','nihao','nisha'], // the prop can be used inside templates, and will also // be set as `this.msg` template: '<span>{{ msg }}{{nihao}}{{nisha}}</span>', /*data: function() { return { msg: 'boy' } }*/ }); var vm = new Vue({ el: '#app1' })
新闻热点
疑难解答
图片精选