7.组件:component
1.父子传值(props)
//1.父组件(冒号传值) <template> <div> <zi-jian :msg1="msg"></zi-jian> </div> </template> <script> import ZiJian from './ZiJian' export default{ components:{ZiJian}, data(){ return{ msg:'父子传值' } } } </script> //2.子组件(props接收值) <template> <div> <h1>{{msg1}}</h1> </div> </template> <script> import ZiJian from './ZiJian' export default{ props:{ msg1:String } } </script>
2.子父传值($emit)
//1.父组件:定义一个fu事件,accept为fu事件的自定义事件 <template> <div> <zi-jian @fu="accept"></zi-jian> </div> </template> <script> import ZiJian from './ZiJian' export default{ components:{ZiJian}, methods:{ accept(info){ console.log('子父传值') } } } </script> //2.子组件:定义一个click点击事件,send为发送事件的执行函数 <template> <div> <button @click="send">点击</button> </div> </template> <script> import ZiJian from './ZiJian' export default{ data(){ return{ info:'子组件向父组件传值' } }, methods:{ send(){ //通过$emit触发父组件的自定义事件fu this.$emit('fu',this.info) } } } </script>
3.同级传值(共用bus)
//1.main.js的同级目录下新建eventBus.js事件 import Vue from "vue" export default new Vue() //2.在组件boy中通过$emit传出值 <template> <button @click="send">点击</button> </template> <script> import EventBus from '../utils/eventBus.js' export default{ data(){ return{ info:'我是boy的数据' } }, methods:{ send(){ EventBus.$emit('boy',this.info) } } } </script> //3.在同级组件girl中通过$on接收值 <template> <div>{{msg}}</div> </template> <script> import EventBus from '../utils/eventBus.js' export default{ data(){ return{ msg:'' } } created(){ var me=this EventBus.$on('boy',function(info){ me.msg=info }) } } </script>
4.动态组件(:is绑定属性)
<template> <div> <keep-alive> //keep-alive保持组件可复用性 <component :is="sex"></component> //:is绑定属性 <button @click="change">切换</button> </keep-alive> </div> </template> <script> import BoyComponent from './BoyComponent' import GirlComponent from './GirlComponent' export default{ components:{ BoyComponent, GirlComponent }, data(){ return{ sex:'BoyComponent' } }, methods:{ change(){ this.sex=this.sex=='BoyComponent'?'GirlComponent':'BoyComponent' } } } </script>
5.子组件不能直接更改父组件传进来的值,必须先保存,后更改
//1.父组件 <template> <div> <boy-component :msg="msg"></boy-component> //将子组件的msg与父组件的msg绑定 </div> </template> <script> import BoyComponent from './BoyComponent' export default{ components:{BoyComponent}, data(){ return{ msg:'我是父组件' } } } </script> //2.子组件 <template> <div>{{msg1}}</div> </template> <script> export default{ props:{ msg1:{ type:String, required:true, validator(value){return value.length<20} } }, data(){ return{ info:'' } }, created(){ this.info=this.msg1 //用info保存父组件传进来的值 console.log(this.info+'test1') //再修改info } } </script>
转载请注明原文链接:https://www.cnblogs.com/chenJieLing/