什么是单向数据流?
组件中的父组件向子组件使用prop进行传值,这个可以称为一个单向数据流,父组件的值发生变化时,子组件的prop的值也会进行更新,这种现象可以称为单向向下的数据绑定(单向下行绑定)
看一个简单的例子进行了解一下:
子组件:
<template>
<input type="text" :value="text" />
</template>
<script>
export default {
name: 'my-input',
props: {
text: String
},
methods: {
}
}
</script>
父组件:
<template>
<div class="home">
<my-input :text="text"></my-input>
</div>
</template>
<script>
import input from '../components/input'
export default {
name: 'Home',
data () {
return {
text: '123'
}
},
components: {
'my-input': input
},
methods: {
}
}
</script>
如果想要父组件的data和子组件prop进行双向数据绑定该怎么写?
默认情况它是单向下行绑定的,props中的属性不会向上传递,所以子组件要借助$emit 方法进行一个数据传输(注意:props中的属性不能直接修改)
话不多说上代码
子组件:
<template>
<input type="text" @input="change" :value="text" />
</template>
<script>
export default {
name: 'my-input',
props: {
text: String
},
methods: {
change (event) {
this.$emit('changeInput', event.target.value)
}
}
}
</script>
父组件:
<template>
<div class="home">
<my-input :text="text" @changeInput="change"></my-input>
</div>
</template>
<script>
import input from '../components/input'
export default {
name: 'Home',
data () {
return {
text: '123'
}
},
components: {
'my-input': input
},
methods: {
change (data) {
this.text = data
}
}
}
</script>