首页 > 语言 > JavaScript > 正文

Vue父子模版传值及组件传值的三种方法

2024-05-06 15:24:08
字体:
来源:转载
供稿:网友

这里是针对于vue1.0,如果要学2.0,建议大家去看官方文档

vue2.0 http://vuefe.cn/guide/

vue-router2.0https://router.vuejs.org/zh-cn/essentials/getting-started.html

第一种

<div id="example">  <my-component></my-component></div><script src="../node_modules/vue/dist/vue.js"></script><script>  //向子组件传递数据  //省略extend方法,vue内部调用  Vue.component('my-component', {    //模板里不支持驼峰的属性写法,需要转换为‘-'连接的属性写法    data:function(){      return{        parentMsg: '雨歇微凉'      }    },    template: '<div>'        +'<input v-model="parentMsg">'        +'<br>'        +'<child-component :my-message="parentMsg"></child-component>'        +'</div>',    components: {      'child-component': {        props: ['myMessage'],        template: '<div>{{myMessage}}</div>'      }    }  });  // 创建根实例1  new Vue({    el: '#example'  });</script>

有什么疑惑的,也可以去查官网的文档,prop传值,这里也可以直接拷去试,如果你有什么更好的简介,还希望能够拿出来分享。

第二种

<div id="example">  <my-component></my-component></div><script src="../node_modules/vue/dist/vue.js"></script><script>  //向子组件传递数据  //省略extend方法,vue内部调用  Vue.component('my-component', {    data:function(){      return {        name:'xiaoming',        age:20      }    },    //模板里不支持驼峰的属性写法,需要转换为‘-'连接的属性写法    template: '<div >{{name}}Parent</div><child1-component v-bind:msg-name="name"></child1-component>',    components: {      'child1-component': {        // 声明 props        props: ['msgName'],        template: '<div>A child-111111 component!{{msgName}}</div>'      }    }  });  // 创建根实例1  new Vue({    el: '#example'  });</script>

第三种

<div id="example">  <my-component></my-component></div><script src="../node_modules/vue/dist/vue.js"></script><script>  //向子组件传递数据  //省略extend方法,vue内部调用  Vue.component('my-component', {    data:function(){      return {        name:'xiaoming',        age:20      }    },    //模板里不支持驼峰的属性写法,需要转换为‘-'连接的属性写法    template: '<div >{{name}}Parent</div><child1-component some="1 + 1"></child1-component><child2-component :some="1 + 3"></child2-component>',     components: {      'child1-component': {        // 声明 props        props: ['some'],        template: '<div>{{some}}</div>',        ready:function(){          console.log(this.some)        }      },      'child2-component': {        // 声明 props        props: ['some'],        template: '<div>{{some}}</div>',        ready:function(){          console.log(this.some)        }      }    }  });  // 创建根实例1  new Vue({    el: '#example'  });</script>            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选