uni-app 小程序环境 vue3 style 函数绑定报错
uni-app 小程序环境 vue3 style 函数绑定报错
| 开发环境 | 版本号 | 项目创建方式 |
|---|---|---|
| Windows | win10 | CLI |
| 第三方开发者工具 | v1.05.2103200 | |
| 基础库 | 2.0.0 | |
| CLI | 4.5.10 |
示例代码:
<template>
<view :style="getStyle"></view>
</template>
<script lang="ts">
import {
defineComponent,
CSSProperties,
computed,
} from 'vue';
export default defineComponent({
props: {
disabled: Boolean,
},
setup(props) {
const getStyle = computed(() => {
const style: CSSProperties = {};
if (props.disabled) {
style.background = '#ccc';
} else {
style.background = '#fff';
}
return style;
});
return {
getStyle,
};
},
});
</script>
操作步骤:
<view :style="getStyle">测试测试</view>
// 另一种写法
<view :style="[getStyle]">测试测试</view>
预期结果:
<view style="{color: #ccc}">测试测试</view>
// 另一种写法
<view style="{color: #ccc}">测试测试</view>
实际结果:
<view style="[object Object]">测试测试</view>
// 另一种写法
报错 TypeError: _vm.__get_style is not a function
bug描述:
小程序环境 vue3 style动态传入绑定报错。 style=“getStyle” 时,渲染结果为:<view style="[object Object]">测试测试</view> style="[getStyle]"时,直接报错:TypeError: _vm.__get_style is not a function
直接在template中写 :style="{color: ‘#ccc’}"是可以渲染成功的。
更多关于uni-app 小程序环境 vue3 style 函数绑定报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
更多关于uni-app 小程序环境 vue3 style 函数绑定报错的实战教程也可以访问 https://www.itying.com/category-93-b0.html
在 uni-app 小程序环境中,Vue3 的 :style 绑定对象时确实存在兼容性问题。根据你的代码和报错信息,核心问题是小程序平台对 Vue3 的响应式对象序列化支持不完整。
问题分析:
style="[object Object]":说明 computed 返回的响应式对象在小程序渲染层被直接调用了toString()。_vm.__get_style is not a function:小程序在解析数组语法时可能触发了异常的类型转换。
解决方案:
方案1:使用字符串形式(推荐)
const getStyle = computed(() => {
if (props.disabled) {
return 'background: #ccc;'
} else {
return 'background: #fff;'
}
});
方案2:使用 toRefs 解构
import { toRefs } from 'vue'
const styleObj = computed(() => ({
background: props.disabled ? '#ccc' : '#fff'
}));
const { value: getStyle } = toRefs(styleObj);
方案3:使用响应式转换
import { reactive, computed, toRefs } from 'vue'
const styleRef = reactive({});
const getStyle = computed(() => {
Object.assign(styleRef, {
background: props.disabled ? '#ccc' : '#fff'
});
return styleRef;
});
临时规避方案:
<view :style="getStyle.value">测试测试</view>
// 或
<view :style="JSON.parse(JSON.stringify(getStyle))">测试测试</view>


