解决uniapp编译的微信小程序不支持v-bind=“$attrs“

1. 环境

1. uniapp
2. vite + vue3 + TypeScript + vite(移动端低代码)
3. 编译成多端通用的小程序

2. 需要分两类解决

  1. v-model属性
  • 在高版本的vue3+vite中使用父组件传递下来的props中的某一个属性,作为当前组件的子组件的v-model入参,那么将会报错
  • [vite] [plugin:vite:vue] v-model cannot be used on a prop, because local prop bindings are not writable. 09:49:27.156 Use a v-bind binding combined with a v-on listener that emits update:x event instead.
  • 正确姿势

    1. 定义一个可读可写的computed
    	const value = computed({
          
          
    	  get: () => props.modelValue,
    	  set: (val) => {
          
          
    	    emits('update:modelValue', val)
    	  }
    	})
    
    1. 将computed直接拿去双向绑定
    	<template>
    	    <uni-easyinput v-model="value"></uni-easyinput>
    	</template>
    
    1. 完整代码
    	// 父组件
    	 <GdFormComponents v-model="formData[val.props.gdSearchItemProp]" />
    	// 子组件 GdFormComponents 
    	<template>
    	    <uni-easyinput v-model="value"></uni-easyinput>
    	</template>
    	
    	<script setup lang='ts'>
    	import  {
          
            type PropType, computed } from 'vue'
    	
    	const props = defineProps({
          
          
    	    modelValue: String as PropType<any>
    	})
    	
    	const  emits = defineEmits(['update:modelValue']);
    	
    	const value = computed({
          
          
    	  get: () => props.modelValue,
    	  set: (val) => {
          
          
    	    emits('update:modelValue', val)
    	  }
    	})
    	
    	</script>
    	
    	<style lang="scss" scoped>
    	
    	</style>
    

2.其他属性

  • 虽然小程序不知持$attrs属性,但是我们还是可以用v-bind

解决方法

  1. 父组件主动传递其他属性attrs
// 父组件
<GdFormComponents 
  v-model="formData[val.props.gdSearchItemProp]" 
  :componentName="val.props.gdChildren[0].componentName" 
  :attrs="val.props.gdChildren[0].props"
/>
  1. v-bind=“attrs”
<template>
    <uni-easyinput v-model="value" v-bind="attrs"></uni-easyinput>
</template>

<script setup lang='ts'>
import  {
    
      type PropType, computed } from 'vue'

const props = defineProps({
    
    
    modelValue: String as PropType<any>,
    componentName: String,
    attrs: {
    
    
        type: Object as PropType<AnyObject>,
        default: () => ({
    
    })
    }
})

const  emits = defineEmits(['update:modelValue']);

const value = computed({
    
    
  get: () => props.modelValue,
  set: (val) => {
    
    
    emits('update:modelValue', val)
  }
})

</script>

<style lang="scss" scoped>

</style>

觉得有用点个赞,让更多的人看见

猜你喜欢

转载自blog.csdn.net/weixin_44441196/article/details/130358038