vue传值处理:vue中父组件通过props传值给子组件,子组件表单控件使用值,子组件改变该值时如何避免报错
话不多说,直接上代码~
父组件father.vue:
<template>
<div class="father">
<child :txt="txt" />
</div>
</template>
<script>
import child from './components/child.vue'
export default {
name:'father',
components:{
child
},
data(){
return {
txt:'11111'
}
}
}
</script>
子组件child.vue使用父组件传的txt值示例1 (非法):
<!--直接使用-->
<template>
<div class="child">
<input type="text" v-model="txt" />
</div>
</template>
<script>
export default{
name:'child',
props:['txt']
}
</script>
这样使用页面初始化是没有问题,但是当input框输入值的时候就会报错:
很显然,这种方式有问题
子组件child.vue使用父组件传的txt值示例2 (非法):
<!--在计算属性computed中直接使用-->
<template>
<div class="child">
<input type="text" v-model="newTxt" />
</div>
</template>
<script>
export default{
name:'child',
props:['txt'],
computed:{
newTxt(){
return this.txt;
}
}
}
</script>
这样使用页面初始化是没有问题,但是当input框输入值的时候就会报错:
很显然,这种方式还是有问题
子组件child.vue使用父组件传的txt值示例3 (推荐):
<!--利用计算属性computed中的get和set复制给新的变量-->
<template>
<div class="child">
<input type="text" v-model="newTxt" />
</div>
</template>
<script>
export default{
name:'child',
props:['txt'],
computed:{
newTxt:{
get(){
return this.txt;
},
set(val){
this.formTxt = val;
}
}
}
}
</script>
这种方式可行,表单提交的时候就直接使用formTxt字段
子组件child.vue使用父组件传的txt值示例4 (推荐):
<!--在生命周期中重新赋值-->
<template>
<div class="child">
<input type="text" v-model="newTxt" />
</div>
</template>
<script>
export default{
name:'child',
props:['txt'],
created() {
this.newTxt = this.txt;
},
data(){
return{
newTxt:''
}
}
}
</script>
在生命周期中重新赋值可行,这种方式可以满足提交数据的时候获取到更改的值newTxt,但是这种方式并不简洁,下面介绍一种更加简洁的方式
子组件child.vue使用父组件传的txt值示例5 (推荐最佳):
<!--先定义一个变量,直接将props接受的值复制到变量上面-->
<template>
<div class="child">
<input type="text" v-model="newTxt" />
</div>
</template>
<script>
export default{
name:'child',
props:['txt'],
data(){
return{
newTxt:this.txt
}
}
}
</script>
很显然这种方式最佳,简洁还得体!