'Computed property not updating in production build
I have a computed property named wildcardItem that is working when using a development build, but when I run the production build (mix --production), the property is no longer updating.
I'm using Laravel Mix to compile the code.
mix.setPublicPath('../')
.js('js/app.js', 'dist/app.js')
.vue()
.postCss('css/app.css', 'dist/app.css', [
require('postcss-import'),
require('@tailwindcss/nesting'),
require('tailwindcss'),
require('autoprefixer'),
])
.options({
manifest: false,
});
Component Setup
const items = ref([]);
const query = ref('');
const wildcardItem = computed(_ => {
console.log('Computing wildcard...');
return {
label: query.value,
};
});
document.addEventListener('CustomEvent', function (event) {
items.value = [
...event.detail.items,
wildcardItem,
];
});
Component Template
<template>
<div>
<input v-model="query" />
<div v-for="(item, index) in items" :key="`item-${index}`">
{{ item.label }}
</div>
</div>
</template>
I also don't see my console.log when running with the production build.
Can someone please guide me on why it's not working? :)
Solution 1:[1]
computed() returns a ref, so you need to use .value to unwrap the ref for the value:
document.addEventListener('CustomEvent', function (event) {
items.value = [
...event.detail.items,
//wildcardItem, ?
wildcardItem.value, ?
];
});
Alternatively, you could use the reactivity transform, which does not require any unwrapping (no .value needed). Instead of importing ref and computed, use $ref and $computed (no imports needed):
<script setup>
let items = $ref([])
let query = $ref('')
const wildcardItem = $computed(_ => {
console.log('Computing wildcard...')
return {
label: query,
}
})
document.addEventListener('CustomEvent', function (event) {
items = [
...event.detail.items,
wildcardItem,
]
})
</script>
Another issue you were seeing was that items was not updated when wildcardItem changed. You would need to refactor your solution to make items a computed property based on the wildcardItem appended to items from the custom event:
<script setup>
import { ref, computed } from 'vue'
const customEventItems = ref([])
const query = ref('')
const wildcardItem = computed(_ => {})
const items = computed(() => [...customEventItems.value, wildcardItem.value])
document.addEventListener('CustomEvent', function (event) {
customEventItems.value = [...event.detail.items]
})
</script>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
