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? :)
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, ✅
];
});
demo 1
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>
demo 2
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>
demo 3
Related
The following code works and I can see the output as intended when use ref, but when using reactive, I see no changes in the DOM. If I console.log transaction, the data is there in both cases. Once transaction as a variable changes, should the changes not be reflected on the DOM in both cases?
I'm still trying to wrap my head around Vue 3's composition API and when to use ref and reactive. My understanding was that when dealing with objects, use reactive and use ref for primitive types.
Using ref it works:
<template>
{{ transaction }}
</template>
<script setup>
import { ref } from 'vue'
let transaction = ref({})
const getPayByLinkTransaction = () => {
axios({
method: "get",
url: "pay-by-link",
params: {
merchantUuid: import.meta.env.VITE_MERCHANT_UUID,
uuid: route.params.uuid,
},
})
.then((res) => {
transaction.value = res.data
})
.catch((e) => {
console.log(e)
})
}
getPayByLinkTransaction()
</script>
Using reactive it doesn't work:
<template>
{{ transaction }}
</template>
<script setup>
import { reactive } from 'vue'
let transaction = reactive({})
const getPayByLinkTransaction = () => {
axios({
method: "get",
url: "pay-by-link",
params: {
merchantUuid: import.meta.env.VITE_MERCHANT_UUID,
uuid: route.params.uuid,
},
})
.then((res) => {
transaction = { ...res.data }
})
.catch((e) => {
console.log(e)
})
}
getPayByLinkTransaction()
</script>
Oh, when you do transaction = { ...res.data } on the reactive object, you override it, like you would with any other variable reference.
What does work is assigning to the reactive object:
Object.assign(transaction, res.data)
Internally, the object is a Proxy which uses abstract getters and setters to trigger change events and map to the associated values. The setter can handle adding new properties.
A ref() on the other hand is not a Proxy, but it does the same thing with its .value getter and setter.
From what I understand, the idea of reactive() is not to make any individual object reactive, but rather to collect all your refs in one single reactive object (somewhat similar to the props object), while ref() is used for individual variables. In your case, that would mean to declare it as:
const refs = reactive({transaction: {}})
refs.transaction = { ...res.data }
The general recommendation seems to be to pick one and stick with it, and most people seem to prefer ref(). Ultimately it comes down to if you prefer the annoyance of having to write transaction.value in your script or always writing refs.transaction everywhere.
With transaction = { ...res.data } the variable transaction gets replaced with a new Object and loses reactivity.
You can omit it by changing the data sub-property directly or by using ref() instead of reactivity()
This works:
let transaction = ref({})
transaction.data = res.data;
Check the Reactivity in Depth and this great article on Medium Ref() vs Reactive() in Vue 3 to understand the details.
Playground
const { createApp, ref, reactive } = Vue;
const App = {
setup() {
const transaction1 = ref({});
let transaction2 = reactive({ data: {} });
const res = { data: { test: 'My Test Data'} };
const replace1 = () => {
transaction1.value = res.data;
}
const replace2 = () => {
transaction2.data = res.data;
}
const replace3 = () => {
transaction2.data = {};
}
return {transaction1, transaction2, replace1, replace2, replace3 }
}
}
const app = Vue.createApp(App);
app.mount('#app');
#app { line-height: 2; }
[v-cloak] { display: none; }
<div id="app">
transaction1: {{ transaction1 }}
<button type="button" #click="replace1()">1</button>
<br/>
transaction2: {{ transaction2 }}
<button type="button" #click="replace2()">2</button>
<button type="button" #click="replace3()">3</button>
</div>
<script src="https://unpkg.com/vue#3/dist/vue.global.prod.js"></script>
Since reactive transaction is an object try to use Object.assign method as follows :
Object.assign(transaction, res.data)
I have following component:
<script setup>
import {computed, onMounted, ref, watch} from "vue";
import {useDialogStore} from "#/store/dialog";
import TableSwitcher from "#/components/Dialogs/Components/TableSwitcher.vue"
let emit = defineEmits(['confirmDialogConfirmed', 'confirmDialogClose'])
let dialogStore = useDialogStore()
let question = computed(() => dialogStore.dialogQuestion)
let mainComponent = ref('')
let props = defineProps({
open: {
type: Boolean,
required: true
},
id: {
type: String,
default: 'main-dialog'
},
component: {
type: String,
required: true,
}
})
watch(props, (newValue, oldValue) => {
mainComponent.value = props.component
console.log(mainComponent);
if(newValue.open === true)
{
dialog.showModal()
}
},
{
deep:true
}
);
let dialog = ref();
let closeDialog = (confirmAction = false) =>
{
dialog.close()
dialogStore.close(confirmAction)
}
onMounted(() => {
dialog = document.getElementById(props.id);
});
</script>
<template>
<dialog :id="id">
<component :is="mainComponent" ></component>
</dialog>
</template>
For activating component I am using this:
<main-dialog
v-if="component"
:component="component"
:open="true">
</main-dialog>
component value is created on click and passed as a prop to the main component. When I click to activate this component I am getting following error:
Invalid vnode type when creating vnode
When I hard code the component name for the mainComponent var the component is loaded correctly. What am I doing wrong here?
There are different ways to solve that. I think in your case it would make sense to use slots. But if you want to keep your approach you can globally define your components in your Vue app.
without slots
const app = createApp({});
// define components globally as async components:
app.component('first-component', defineAsyncComponent(async () => import('path/to/your/FirstComponent.vue'));
app.component('second-component', defineAsyncComponent(async () => import('path/to/your/SecondComponent.vue'));
app.mount('#app');
Then you can use strings and fix some bugs in your component:
Don’t use ids, instead use a template ref to access the dialog element
Use const instead of let for non-changing values.
props are already reactive so you can use the props also directly inside your template and they will be updated automatically when changed from the outside.
// inside <script setup>
import {computed, onMounted, ref, watch} from "vue";
import {useDialogStore} from "#/store/dialog";
import TableSwitcher from "#/components/Dialogs/Components/TableSwitcher.vue"
// use const instead of let, as the values are not changing:
const emit = defineEmits(['confirmDialogConfirmed', 'confirmDialogClose'])
const props = defineProps({
open: {
type: Boolean,
required: true
},
id: {
type: String,
default: 'main-dialog'
},
component: {
type: String,
required: true,
}
});
const dialogStore = useDialogStore()
const question = computed(() => dialogStore.dialogQuestion);
const dialog = ref(null);
watchPostEffect(
() => {
if(props.open) {
dialog.value?.showModal()
}
},
// call watcher also on first lifecycle:
{ immediate: true }
);
let closeDialog = (confirmAction = false) => {
dialog.value?.close()
dialogStore.close(confirmAction)
}
<!-- the sfc template -->
<dialog ref="dialog">
<component :is="props.component" />
</dialog>
with slots
<!-- use your main-dialog -->
<main-dialog :open="open">
<first-component v-if="condition"/>
<second-component v-else />
</main-dialog>
<!-- template of MainDialog.vue -->
<dialog ref="dialog">
<slot />
</dialog>
I am wondering how to destructure an object prop without having to type data.title, data.keywords, data.image etc. I've tried spreading the object directly, but inside the template it is undefined if I do that.
Would like to return directly {{ title }}, {{ textarea }} etc.
My code:
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
<script lang="ts">
import { useSanityFetcher } from "vue-sanity";
import { defineComponent, reactive, toRefs } from "vue";
export default defineComponent({
name: "App",
setup: () => {
const articleQuery = `*[_type == "article"][0] {
title,
textarea,
}`;
const options = {
listen: true,
clientOnly: true,
};
const res = useSanityFetcher<any | object>(articleQuery, options);
const data = reactive(res.data);
return toRefs(data);
},
});
</script>
Considering that useSanityFetcher is asynchronous, and res is reactive, it's incorrect to access res.data directly in setup because this disables the reactivity. Everything should happen in computed, watch, etc callback functions.
title, etc properties need to be explicitly listed in order to map reactive object to separate refs with respective names - can probably be combined with articleQuery definition or instantly available as res.data keys
E.g.:
const dataRefs = Object.fromEntries(['title', ...].map(key => [key, ref(null)]))
const res = ...
watchEffect(() => {
if (!res.data) return;
for (const key in dataRefs)
dataRefs[key] = res.data[key];
});
return { ...dataRefs };
Destructuring the object is not the problem, see Vue SFC Playground
<script lang="ts">
//import { useSanityFetcher } from "vue-sanity";
import { defineComponent, reactive, toRefs } from "vue";
export default defineComponent({
name: "App",
setup: () => {
const res = {
data: {
title: 'Hi there'
}
}
const data = reactive(res.data);
return toRefs(data);
},
});
</script>
<template>
<div>
<h1>{{ title }}</h1>
</div>
</template>
It may simply be the space between the filter and the projection in the GROQ expression
const articleQuery = `*[_type == "article"][0]{ title, textarea }`;
See A description of the GROQ syntax
A typical GROQ query has this form:
*[ <filter> ]{ <projection> }
The Vue docs actually recommend not destructing props because of the way reactivity works but if you really want to something like this should work:
const res = useSanityFetcher<any | object(articleQuery, options);
const data = reactive(res.data);
return toRefs(data);
Don't forget to import reactive and toRefs.
I've read several posts on stackoverflow and other websites, but still can't figure out what's going wrong in my case.
I'm building an app following composition api approach and using a variable called modelStartDate (which I initiate at Jan 3, 2022). This is how my store looks:
import { createStore } from 'vuex'
export default createStore({
state: {
modelStartDate: new Date(2022, 0, 3)
},
mutations: {
modelStartDateMutation(state, newDate) {
state.modelStartDate = newDate
}
},
actions: {
},
getters: {
},
modules: {
}
})
In the relevant Vue file, I have the following code snippet:
<template>
<nav class="left-bar">
<div class="block" id="modelStartDate">
<label>Model start date</label>
<input type="date" v-model="modelStartDateProxy" />
</div>
<p>{{ modelStartDate }}</p>
</nav>
</template>
<script>
import { ref } from '#vue/reactivity'
import { useStore } from 'vuex'
import { computed } from '#vue/runtime-core'
export default {
setup() {
const store = useStore()
const modelStartDateProxy = computed({
get: () => store.state.modelStartDate,
set: (newDate) => store.commit("modelStartDateMutation", newDate)
})
const modelStartDate = store.state.modelStartDate
return { modelStartDateProxy, modelStartDate }
}
}
</script>
When I run the page, the paragraph tag prints the right date, however the input tag, where the user can change the date, is empty (I was expecting Jan 3, 2022 to be pre-selected). When the date is changed, nothing seems to change in the app. I'm getting no errors. Any idea what I'm doing incorrectly?
Also, can I access store's modelStartDate state without having to define it separately (redundantly?) in the vue setup() section?
First, I don't know which tutorial you read. But to me, the problem is here:
const modelStartDateProxy = computed({
get: () => store.state.modelStartDate,
set: (newDate) => store.commit("modelStartDateMutation", newDate)
})
const modelStartDate = store.state.modelStartDate
The snippet
const modelStartDateProxy = computed({
get: () => store.state.modelStartDate,
set: (newDate) => store.commit("modelStartDateMutation", newDate)
})
is weird to me.
Duplicate of store.state.modelStartDate. DRY.
<p>{{ modelStartDate }}</p> render data from const modelStartDate = store.state.modelStartDate. But the data was only assign once. So the new value was not render on input was changed.
Solution:
const modelStartDate = computed(() => store.state.modelStartDate);
You can take a look at this playground.
The html element input returns a string: "YYYY-MM-DD". Therefore you need the syntax new Date(value)
Take a look at this playground
<template>
<label>Model start date</label>
<input type="date" v-model="modelStartDateProxy" />
<p>{{ modelStartDateProxy }}</p>
</template>
<script>
import { store } from './store.js' //mock-up store
import { ref, computed } from 'vue'
export default {
setup() {
const modelStartDateProxy = computed({
get: () => store.state.modelStartDate,
set: (newDate) => store.commit(newDate) // Use real Vuex syntax
})
return { modelStartDateProxy }
}
}
</script>
//Mock-up Store (not real vuex)
import {reactive} from 'vue'
export const store = reactive({
state: {
modelStartDate: new Date(2022, 0, 3)
},
commit: (value) => store.state.modelStartDate = new Date(value) // new Date(value)
})
<template>
<div>
<h1>{{ counter }}</h1>
<input type="text" v-model="counter" />
</div>
</template>
<script>
import { computed } from 'vue'
import { useStore } from 'vuex'
export default {
setup() {
const store = useStore()
const counter = computed(() => store.state.counter)
return { counter }
},
}
</script>
How to change value of counter in the store when input value changes
I am getting this error in the console:
[ operation failed: computed value is readonly ]
Try this:
...
const counter = computed({
get: () => store.state.counter,
set: (val) => store.commit('COUNTER_MUTATION', val)
})
...
https://v3.vuejs.org/api/computed-watch-api.html#computed
Try this:
<input v-model="counter">
computed: {
counter: {
get () {
return this.$store.state.a
},
set (value) {
this.$store.commit('updateA', value)
}
}
}
With composition API
When creating computed properties we can have two types, the readonly and a writable one.
To allow v-model to update a variable value we need a writable computed ref.
Example of a readonly computed ref:
const
n = ref(0),
count = computed(() => n.value);
console.log(count.value) // 0
count.value = 2 // error
Example of a writable computed ref:
const n = ref(0)
const count = computed({
get: () => n.value,
set: (val) => n.value = val
})
count.value = 2
console.log(count.value) // 2
So.. in summary, to use v-model with Vuex we need to use a writable computed ref. With composition API it would look like below:
note: I changed the counter variable with about so that the code makes more sense
<script setup>
import {computed} from 'vue'
import {useStore} from 'vuex'
const store = useStore()
const about = computed({
get: () => store.state.about,
set: (text) => store.dispatch('setAbout', text)
})
</script>
<template>
<div>
<h1>{{ about }}</h1>
<input type="text" v-model="about" />
</div>
</template>