为什么80%的码农都做不了架构师?>>>
首先是父组件与子组件沟通
父组件告诉子组件,“嘿,孩子,我有话和你说”
组件A代码
<template><section><h1>这是组件</h1><test-B :chile-name="undefined" :chile-age="undefined"></test-B></section> </template><script>import testB from "./testB"export default {name: "testA",data () {return {name:"meiqin",age:18}},components:{testB},} </script>
注意:父组件给子组件传值时候的写法,冒号,必须使用-代替驼峰。
这里的data不是一个对象,而是函数。
子组件就使用props来收听。
<template><section><h1>这是B组件</h1><div>my name is {{chileName}},my age is {{chileAge}}</div></section></template><script>export default {name: "testA",data () {return{name1 : "meiqin"}},props:{chileName:{type:String,default:"qiunnan" },chileAge:{type:Number,default:100}}} </script>
props接收三种写法,一是直接接收,类型是数组。二限制类型,是对象;三限制类型和默认值,是个对象
子组件与父组件沟通
父组件在子组件引用上面,设置监听子组件。子组件绑定触发事件,只要一发生改变,父组件就会监听到。
子组件B
<template><section @click="funcB"><hr><h1>这是B组件</h1><div>my name is {{chileName}},my age is {{chileAge}}</div><button @click="change">按钮</button><button @click="aa">按钮AA</button><div>{{msg}}</div></section></template><script>export default {name: "testA",data () {return{msg : "爸爸去哪里了"}},props:{chileName:{type:String },chileAge:{type:Number}},methods:{funcB() {this.$emit('funcBBB',this.msg)},change() {this.msg = "爸爸在北京"},aa(){}}} </script>
父组件A
<template><section><h1>这是A组件</h1><div>这是子组件说话:{{msg}}</div><test-B @funcBBB="change" :chile-name="name" :chile-age="age" ></test-B></section> </template><script>import testB from "./testB"export default {name: "testA",data () {return {name:"meiqin",age:18,msg: ''}},components:{ testB },methods:{change (msg) {console.log(msg)this.msg = msg;}},} </script>
注意点:
funcBBB要对应,this.$emit('funcBBB',this.msg)与 <test-B @funcBBB="change" :chile-name="name" :chile-age="age" ></test-B>
只要子模板发生变化,就会触发change。
函数的写法错误,导致报错
funcB: () =>{ //错误的写法this.$emit('funcB',"msg") }, change () {this.msg = "爸爸在北京" }
非父子组件的话
先记下实例
发送方
xgg (cell) {Bus.$emit('xgg', cell)this.$emit('xgg') //这句是与父组件进行交流 }
非父子组件接收方
mounted () {Bus.$on('xgg', cell => {var arr1 = cell.food_senior_standardsthis.standardArr = arr1.map(() => false)this.currentCount = 0this.combinationId = ''this.price = ''this.food = cell}) }, destroyed () {Bus.$off('xgg') },
父组件监听
<food-list v-show="tabed == 1" @xgg="shwoTaste = true">