Vue中父组件传值到子组件
Vue中父组件传值分为两步:
一、父组件中代码中,使用属性绑定向子组件传递数据,
如图, 其中,:titles="title"就是在将父组件的title属性值,传递到子组件所绑定的titles属性中,这时候,子组件就有了一个带有值的titles属性了
<template> <div class="parent"> <h1>我是父组件</h1> <childVue :titles="title" :contents="content"></childVue> </div> </template> <script> import childVue from './child.vue' export default { name: 'parant', components:{ childVue }, data() { return { content: "我是父组件传过来的内容" }; } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style lang="scss" scoped> .parent{ width: 500px; height: 500px; background: rgb(146, 133, 133); } </style>
复制
二、子组件需要接收传过来的属性值
如下代码,子组件需要使用props属性去接受刚刚父组件传递过来的属性titles和contents,需要定义一下属性类型哦
<template> <div class="child"> <h2>我是子组件</h2> <h4>{{titles}}</h4> <h4>{{contents}}</h4> </div> </template> <script> export default { name: 'helloChild', props: { titles: String, contents: String } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> .child{ width: 400px; height: 300px; background: rgb(157, 117, 117); } </style>
复制
总结一下:
父组件中引入子组件、注册子组件,tempalte中使用子组件; import 、components、
子组件: props中创建一个属性,接受父组件传的值;
在template中使用 {{contents}};
父组件中的 , :title与子组件中prop添加的属性名称要一致;
=”title“与父组件中data数据中的title名称要一致;
props绑定的写法也可以写成这样的形式
props: { title: { type: String, // [String, Number], default: 1 } }
复制
Vue中子组件传值到父组件
子组件传值到父组件也有两步。
一:子组件通过$emit触发一个自定义事件,传递属性出去
如下,通过按钮(也可以其它方式,能触发$emit即可),触发$emit方法,传递datas的值出去
<template> <div> <h1>children</h1> <button @click="sendTOParent">向父组件传值</button> </div> </template>> <script> export default { data() { return { datas: "子组件中的信息" }; }, methods:{ sendTOParent(){ this.$emit('listenToChildEvent',this.data) } } }; </script>>
复制
2.在父组件中引用子组件的标签中,使用v-on监听该自定义事件并添加一个响应该事件的处理方法
<template> <div> <h1>我是父组件</h1> <children v-on:listenToChildEvent = 'showMsgfromChild'></children> </div> </template>> <script> import Children from "./Children"; export default { data() { return { }; }, methods:{ showMsgfromChild(data){ console.log(data) } }, components: { Children }, }; </script>
复制
总结:
子组件通过$emit传递参数出去,在父组件中引用子组件的标签中,使用v-on监听该自定义事件并添加一个响应该事件的处理方法