Vue3解决ref赋值为require(’’)时数据无法响应问题

问题代码:

const useIcon = () => {
    let iconSrc = ref('');
    let setupModelShow = ref(false);
	
	iconSrc = require('../assets/img/url.png');
	
    const handleServe = () => {
        iconSrc = setupModelShow.value ? require('../assets/img/url.png') : require('../assets/img/url-active.png');
        console.log(iconSrc);
        setupModelShow.value = !setupModelShow.value;
    }

    return {
        iconSrc,
        setupModelShow,
        handleServe,
    }
};

上面代码中iconSrc确实在变化,但页面上并没有更新。

问题原因:ref()只能监听简单数据类型,此处应监听为字符串,而不是直接监听require()返回值(require()返回值是一个模块)。

问题解决(将require()返回值显示转化为String类型即可):

const useIcon = () => {
    let iconSrc = ref(String(require('../assets/img/url.png')));
    let setupModelShow = ref(false);

    const handleServe = () => {
        iconSrc.value = setupModelShow.value ? require('../assets/img/url.png') : require('../assets/img/url-active.png');
        setupModelShow.value = !setupModelShow.value;
    }

    return {
        iconSrc,
        setupModelShow,
        handleServe,
    }
};
Logo

前往低代码交流专区

更多推荐