input封装为子组件 更改值报错

出现这个问题的原因是 input的v-model本身就是语法糖,本质是value props,因此需要在子组件中用别的值替代掉传入的props。

下面上代码

子组件的代码:

<template>
	<view class="list-input">
		<view class="left">
			{{title}}
		</view>
		<view class="right">
			<input type="text" v-model="msg" :placeholder="placeholderMsg" placeholder-style="font-size: 26upx"/>
		</view>
	</view>
</template>

<script>
	export default {
		props:{
			inputMsg: {
				type: String,
				default: ""
			},
			placeholderMsg:{
				type: String,
				default: ""
			},
			title: {
				type: String,
				default: ""
			}
			
		},
		watch:{
			inputMsg(nval,oval){
				if(nval!=oval){
					this.msg = nval
				}
			},
			msg(nval,oval){
				if(nval!=oval){
					this.$emit('input',nval)
				}
			}
			
		},
		data() {
			return {
				msg: ''
			}
		},
		methods: {
		
		}
	}
</script>

 父组件的代码:

			<new-input v-model="info.name" title="姓名" :inputMsg="info.name"  placeholderMsg="请输入姓名"></new-input>

父组件也需要加入 v-model ,子组件使用this.$emit('input')就行

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue中,props是单向数据流,只能由父组件向子组件传递数据,子组件不应该直接修改props的。如果子组件需要修改props的,应该通过事件的方式向父组件发送消息,由父组件来修改props的。 如果子组件直接修改props的,会报出一个警告,如下所示: ``` [Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "message" ``` 这个警告的意思是,不要直接修改props的,因为父组件重新渲染时,props的会被覆盖。应该使用一个基于props的的data或computed属性。 下面是一个示例,演示如何通过事件向父组件发送消息,让父组件来修改props的: 父组件: ``` <template> <div> <child :message="message" @update-message="handleUpdateMessage"></child> </div> </template> <script> import Child from './Child.vue' export default { components: { Child }, data() { return { message: 'Hello World!' } }, methods: { handleUpdateMessage(newMessage) { this.message = newMessage } } } </script> ``` 子组件: ``` <template> <div> <input v-model="localMessage"> <button @click="sendMessage">发送消息</button> </div> </template> <script> export default { props: { message: { type: String, required: true } }, data() { return { localMessage: this.message } }, methods: { sendMessage() { this.$emit('update-message', this.localMessage) } } } </script> ``` 在子组件中,我们使用一个名为localMessage的data属性来保存props的,然后在发送事件时,将localMessage作为参数传递给父组件,让父组件来修改props的
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值