1. 父组件向子组件进行传值
<template>
<div>
父组件:
<input type="text" v-model="name">
<br>
<br>
<child :inputName="name">child>
div>
template>
<script>
import child from './child'
export default {
components: {
child
},
data () {
return {
name: ''
}
}
}
script>
子组件:
<template>
<div>
子组件:
<span>{{inputName}}span>
div>
template>
<script>
export default {
// 接受父组件的值
props: {
inputName: String,
required: true
}
}
script>
2. 子组件向父组件传值
子组件
<template>
<div>
子组件:
<span>{{childValue}}span>
<input type="button" value="点击触发" @click="childClick">
div>
template>
<script>
export default {
data () {
return {
childValue: '我是子组件的数据'
}
},
methods: {
childClick () {
// childByValue是在父组件on监听的方法
// 第二个参数this.childValue是需要传的值
this.$emit('childByValue', this.childValue)
}
}
}
script>
父组件
<template>
<div>
父组件:
<span>{{name}}span>
<br>
<br>
<child v-on:childByValue="childByValue">child>
div>
template>
<script>
import child from './child'
export default {
components: {
child
},
data () {
return {
name: ''
}
},
methods: {
childByValue: function (childValue) {
// childValue就是子组件传过来的值
this.name = childValue
}
}
}
script>