父组件向子组件传值
- 子组件在prop中创建一个属性,以接收父组件传过来的值
- 父组件中注册子组件
- 在子组件标签中添加子组件props中创建的属性
- 把需要传给子组件的值赋给该属性
子组件在props中创建一个或多个属性,以接收父组件传过来的值
<template>
<div>
<h1>这是子组件</h1>
<p>{{message}}</p>
</div>
</template>
<script>
export default {
name: 'specsInput',
props: ["message","title"]
}
</script>
父组件中注册子组件
在子组件标签中添加子组件props中创建的属性 message
把需要传给子组件的值赋给该属性 message = "hello"
<template>
<div id="app">
<specs-input message="parentMsg"></specs-input>
</div>
</template>
<script>
import specInput from './specInput'
export default {
name: 'app',
data(){
return{
parentMsg: "hello, you are my son!"
}
},
components:{
specInput
}
}
</script>
以上,简单的介绍了父像子传入的一个静态的值的方法。
prop可以通过v-bind动态赋值
<!-- 动态赋予一个变量的值 -->
<specs-input v-bind:message="hello" v-bind:title="post.title"></specs-input>
<!-- 动态赋予一个复杂表达式的值 -->
<specs-input v-bind:message="hello" v-bind:title="post.title"></specs-input>
子组件向父组件传值
- 子组件中需要以某种方式例如点击事件的方法来触发一个自定义事件
- 将需要传的值作为$emit的第二个参数,该值将作为实参传给响应自定义事件的方法
- 在父组件中注册子组件并在子组件标签上绑定对自定义事件的监听
<template>
<div>
<h2>child子组件部分</h2>
<p>{{message}}</p>
<button v-on:click="sendMsgToParent">向父组件传值</button>
</div>
</template>
<script>
export default {
name: 'specsInput',
props: ["message","title"],
methods:{
sendMsgToParent:function(){
this.$emit("listenTochildEvent","this message is from child")
}
}
}
</script>
- 在父组件中注册子组件并在子组件标签上绑定对子组件自定义事件的监听
<template>
<div id="app">
<specs-input message="parentMsg" v-on:listenTochildEvent=“showMsgFromChild”></specs-input>
</div>
</template>
<script>
import specInput from './specInput'
export default {
name: 'app',
data(){
return{
parentMsg: "hello, you are my son!"
}
},
components:{
specInput
},
methods:{
showMsgFromChild: function(data){
console.log(data);
}
}
}
</script>
==总结, 父子间传值,需要一个中间介质。父向子是props中的属性。 子向父是自定义事件,通过$emit将值传给自定义事件,接收端父绑定并监听自定义是事件。 ==