· 父组件向子组件传递参数
child.vue如下
<template>
<div class="childClass">
<h3>子组件内容</h3>
<p :class="num==6?redclass:blueclass">当父组件内容传递给子组件时,该行变成红色</p>
<p>父组件向子组件传递的参数是:{{num}}</p>
</div>
</template>
<style lang='css'>
.redclass {
color:red;
}
.blueclass {
color:blue;
}
</style>
<script>
export default {
data(){
return {
redclass:'redclass',
blueclass:'blueclass',
}
},
props:['num'], //使用字符串数组的形式!!
// props:{ //当props是一个对象时,他包含验证要求
// num:{
// type:Number,
// default:100,
// },
// }
}
</script>
parent.vue如下
<template>
<div cals="parent">
<h3>这是父组件的内容</h3>
<hr>
<Child :num="parentNum"></Child>
</div>
</template>
<script>
import Child from './child.vue'
export default {
components:{ Child },
data(){
return {
parentNum:6,
}
},
}
</script>
实现原理如下:
· 子组件在props中创建一个属性如上的num,用来接收父组件中传递过来的值;
· 父组件中注册子组件,如components:{Child}
· 父组件中使用子组件标签,并在子组件标签中添加子组件props中创建的属性,如 <Child :num=””></Child>
· 把需要传递给子组件的值赋值给该属性,如<Child :num=”value”></Child>
------------------------------------------------------------------------------------------
· 子组件向父组件传递参数
parent.vue如下
<template>
<div cals="parent">
<h3>这是父组件的内容</h3>
<p :class='num==8?redclass:blueclass'>当子组件向父组件传递参数成功后,该行文字变红色</p>
<p>父组件从子组件获取的参数是:{{num}}</p>
<hr>
<Child @listenToChildEvent="showMsgFromChild"></Child>
</div>
</template>
<style>
.redclass {
color:red;
}
.blueclass {
color:blue;
}
</style>
<script>
import Child from './child.vue'
export default {
components:{ Child },
data(){
return {
num:0, //声明需要接受子组件参数的属性
redclass:'redclass',
blueclass:'blueclass',
}
},
methods:{
showMsgFromChild(data){
this.num=data; //将子组件触发该事件时传递的参数赋值给父组件的属性
console.log(data);
}
}
}
</script>
child.vue如下
<template>
<div class="childClass">
<h3>子组件内容</h3>
<p>子组件向父组件传递的参数是:{{childNum}}</p>
<button @click="sendMsgToParent()">点击传递参数</button>
</div>
</template>
<script>
export default {
data(){
return {
childNum:8,
}
},
methods:{
sendMsgToParent(){
this.$emit('listenToChildEvent',this.childNum);
}
}
}
</script>
实现原理如下:
·父组件使用子组件标签,子组件标签中使用 v-on绑定自定义事件来监听该事件的触发 ,以及该自定义事件的相应函数(接收处理子组件传递的参数),如<Child @listenToChildEvent="showMsgFromChild()"></Child> showMsgFromChild(data){ this.num=data; }
·子组件中触发该自定义事件,并传递子组件中的参数,如
sendMsgToParent(){ this.$emit('listenToChildEvent',this.childNum); }
注意:
1、props是可以是字符串数组,也可以是对象(可以类型验证、设置默认值等) ;
2、使用.native修饰监听事件,开发中使用了element-ui 的框架标签时候,使用事件绑定无效。这时候需要使用.native 修饰v-on:event ,可以在框架标签或组件的根元素上监听一个原生事件,例如
<my-component v-on:click.native="doTheThing"></my-component>