产品网站设计,代做网站,推广软文怎么写,宁波seo外包semVue中父组件传值到子组件
Vue中父组件传值分为两步#xff1a; 一、父组件中代码中#xff0c;使用属性绑定向子组件传递数据#xff0c; 如图, 其中#xff0c;:titlestitle就是在将父组件的title属性值#xff0c;传递到子组件所绑定的titles属性中#x…Vue中父组件传值到子组件
Vue中父组件传值分为两步 一、父组件中代码中使用属性绑定向子组件传递数据 如图, 其中:titlestitle就是在将父组件的title属性值传递到子组件所绑定的titles属性中这时候子组件就有了一个带有值的titles属性了
templatediv classparenth1我是父组件/h1childVue :titlestitle :contentscontent/childVue/div
/templatescript
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 langscss scoped
.parent{width: 500px;height: 500px;background: rgb(146, 133, 133);}
/style二、子组件需要接收传过来的属性值 如下代码子组件需要使用props属性去接受刚刚父组件传递过来的属性titles和contents需要定义一下属性类型哦
templatediv classchildh2我是子组件/h2h4{{titles}}/h4h4{{contents}}/h4/div
/templatescript
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的值出去
templatedivh1children/h1button clicksendTOParent向父组件传值/button/div
/template
script
export default {data() {return {datas: 子组件中的信息};},methods:{sendTOParent(){this.$emit(listenToChildEvent,this.data)}}
};
/script2.在父组件中引用子组件的标签中使用v-on监听该自定义事件并添加一个响应该事件的处理方法
templatedivh1我是父组件/h1children 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监听该自定义事件并添加一个响应该事件的处理方法