Vue 3: How to Access Setup Variable in Component Function - javascript

Consider the following simple example using the composition API in Vue 3. I'm trying to have an instance of test available in the functions of my component.
<script>
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
name: 'Test',
setup(){
let test = ref()
onMounted(() => {
doSomething()
})
return{
test,
doSomething
}
}
})
function doSomething(){
console.log(test) //<-- undefined
console.log(this.test) //<-- undefined
}
</script>
How do I access test inside doSomething()? My understanding is that anything returned by setup() should be available throughout the component much like a data() attributes from the options API.

you have to pass the ref as a parameter
<script>
import { defineComponent, ref, onMounted } from 'vue'
export default defineComponent({
name: 'Test',
setup () {
let test = ref(null)
onMounted(() => {
doSomething(test.value)
})
return {
test,
doSomething
}
}
})
function doSomething (param) {
console.log(param); // null
}
</script>
another approach:
// functions.js
import { ref } from 'vue'
export let test = ref(null)
// vue-file
<script>
import { defineComponent, ref, onMounted } from 'vue'
import { test } from '../utils/functions.js'
export default defineComponent({
name: 'Test',
setup () {
onMounted(() => {
doSomething(test)
})
return {
test,
doSomething
}
}
})
function doSomething (param) {
console.log(test.value); // <-- instant access
console.log(param.value); // <-- import via parameter
}
</script>

Related

How can I modify the value of state in pinia in vue3 component test and affect the component?

Using vue-test-utils to test the component using pinia, I need to modify the value of the state stored in pinia, but I have tried many methods to no avail. The original component and store files are as follows.
// HelloWorld.vue
<template>
<h1>{{ title }}</h1>
</template>
<script>
import { useTestStore } from "#/stores/test";
import { mapState } from "pinia";
export default {
name: "HelloWorld",
computed: {
...mapState(useTestStore, ["title"]),
},
};
</script>
// #/stores/test.js
import { defineStore } from "pinia";
export const useTestStore = defineStore("test", {
state: () => {
return { title: "hhhhh" };
},
});
The following methods have been tried.
Import the store used within the component to the test code and make changes directly, but the changes cannot affect the component.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
import { useTestStore } from "#/stores/test";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia()],
},
});
const store = useTestStore();
store.title = "xxxxx";
console.log(wrapper.text()) //"hhhhh";
});
Using the initialState in an attempt to overwrite the contents of the original store, but again without any effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia({ initialState: { title: "xxxxx" } })],
},
});
console.log(wrapper.text()) //"hhhhh";
});
Modify the TestingPinia object passed to global.plugins in the test code, but again has no effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const pinia = createTestingPinia();
pinia.state.value.title = "xxxxx";
const wrapper = mount(HelloWorld, {
global: {
plugins: [pinia],
},
});
console.log(wrapper.text()) //"hhhhh";
});
Use global.mocks to mock the states used in the component, but this only works for the states passed in with setup() in the component, while the ones passed in with mapState() have no effect.
// test.spec.js
import { mount } from "#vue/test-utils";
import { createTestingPinia } from "#pinia/testing";
import HelloWorld from "#/components/HelloWorld.vue";
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: {
plugins: [createTestingPinia()],
mocks: { title: "xxxxx" },
},
});
console.log(wrapper.text()) //"hhhhh"
});
This has been resolved using jest.mock().
import { mount } from "#vue/test-utils";
import { createPinia } from "pinia";
import HelloWorld from "#/components/HelloWorld.vue";
jest.mock("#/stores/test", () => {
const { defineStore } = require("pinia");
const useTestStore = defineStore("test", { state: () => ({ title: "xxxxx" }) });
return { useTestStore };
});
test("pinia in component test", () => {
const wrapper = mount(HelloWorld, {
global: { plugins: [createPinia()] },
});
expect(wrapper.text()).toBe("xxxxx");
});
Thanks to Red Panda for this topic. I use "testing-library", and "vue-testing-library" instead of "vue-test-utils" and "jest", but the problem is the same - couldn't change pinia initial data of the store.
I finally found a solution for this issue without mocking the function.
When you $patch data, you just need to await for it. Somehow it helps. My code looks like this and it totally works:
Popup.test.js
import { render, screen } from '#testing-library/vue'
import { createTestingPinia } from '#pinia/testing'
import { popup } from '#/store1/popup/index'
import Popup from '../../components/Popup/index.vue'
describe('Popup component', () => {
test('displays popup with group component', async () => {
render(Popup, {
global: { plugins: [createTestingPinia()] }
})
const store = popup()
await store.$patch({ popupData: 'new name' })
screen.debug()
})
})
OR you can set initialState using this scheme:
import { render, screen } from '#testing-library/vue'
import { createTestingPinia } from '#pinia/testing'
import { popup } from '#/store1/popup/index'
import Popup from '../../components/Popup/index.vue'
test('displays popup with no inner component', async () => {
const { getByTestId } = render(Popup, {
global: {
plugins: [
createTestingPinia({
initialState: {
popup: {
popupData: 'new name'
}
}
})
]
}
})
const store = popup()
screen.debug()
})
Where popup in initialState - is the imported pinia store from #/store1/popup. You can specify any of them there the same way.
Popup.vue
<script>
import { defineAsyncComponent, markRaw } from 'vue'
import { mapState, mapActions } from 'pinia'
import { popup } from '#/store1/popup/index'
export default {
data () {
return {}
},
computed: {
...mapState(popup, ['popupData'])
},
....
I'm working on a project using Vue 3 with composition API styling.
Composition API is used for both components and defining my store.
Here is my store
player.js
import { defineStore } from 'pinia'
import { ref, reactive } from 'vue'
export const usePlayerStore = defineStore('player',()=>{
const isMainBtnGameClicked = ref(false)
return { isMainBtnGameClicked }
})
MyComponent.vue
//import { usePlayerStore } from '...'
const playerStore = usePlayerStore()
playerStore.isMainBtnGameClicked = true
isMainBtnGameClicked from my store is updated properly.
You can also update variables from components by passing them by reference to the pinia store. It's working in my project.
For sake of saving future me many hours of trouble, there is a non-obvious thing in play here - the event loop. Vue reactivity relies on the event loop running to trigger the cascade of state changes.
When you mount/shallowMount/render a component with vue-test-utils, there is no event loop running automatically. You have to trigger it manually for the reactivity to fire, e.g.
await component.vm.$nextTick;
If you don't want to mess around with ticks, you have to mock the store state/getters/etc. (which the docs strongly lean toward, without explaining the necessity). Here OP mocked the whole store.
See also: Vue-test-utils: using $nextTick multiple times in a single test

Vue Composition Api - call child component's method which uses render function

I'm using Vue composition-api with Vue2.
I ran into a problem when I tried to call a method of a component with a render function from its parent.
Without render function, it's ok.
TemplateComponent.vue
<template>
...
</template>
<script lang="ts">
import { defineComponent } from '#vue/composition-api'
export default defineComponent({
setup (props, context) {
const doSomething = () => {
console.log('doSomething')
}
return {
// publish doSomething method.
doSomething
}
}
})
</script>
So, parent component can call TemplateComponent's method like this.
TopPage.vue
<template>
<TemplateComponent ref="componentRef" />
</template>
<script lang="ts">
import { defineComponent, ref, onMounted } from '#vue/composition-api'
import TemplateComponent from '#/components/TemplateComponent.vue'
export default defineComponent({
components: { TemplateComponent },
setup (props, context) {
const componentRef = ref()
onMounted(() => {
componentRef.value.doSomething()
})
}
})
</script>
With render function, I can't find way to call method.
RenderComponent.vue
<script lang="ts">
import { defineComponent, h } from '#vue/composition-api'
export default defineComponent({
components: { TemplateComponent },
setup (props, context) {
const doSomething = () => {
console.log('doSomething')
}
// setup method should return render function.
return () => h('div', 'Hello world!!')
}
})
</script>
When declare render function with composition api, we should return render function in setup method.
https://v3.vuejs.org/guide/composition-api-setup.html#usage-with-render-functions
In this case, I don't understand how to publish doSomething method.
Is there a way to solve this problem?
expose context method exists to combine render function and public instance methods in setup:
context.expose({ doSomething })
return () => ...

Vue 3 - Options API vs Composition API - Load external file into component

I have the following file which is an external file with functions (language.js). I also have created a other component which needs to use language.js (it needs to use the languageText funcion inside language.js). I did used it in a Composition API component. But now I want to get it working in a Options API component. Please check the function inside methods called languageSelector. Inside this function I want to use the global function from language.js (languageText())
Any help?
Options API template (Form.vue)
<script>
import languageText from '#/composables/language';
export default defineComponent({
name: 'Form',
props: {
processingData: Object,
formData: Object
},
emits: ["gateway"],
components: {
Icon
},
data() {
return {
fieldData: this.formData,
}
},
methods: {
languageSelector(data) {
const h = languageText(data) **I want to USE the FUNCTION here.**
console.log(h)
return languageText(data)
},
}
language.js
import { ref, computed, watch } from 'vue';
import { useI18n } from "vue-i18n";
import { useStore } from "vuex";
export default function language() {
const store = useStore();
const i18n = useI18n();
const language = computed(() => {
return store.getters.currentUser.language;
});
function languageText(json) {
const obj = JSON.parse(json)
return obj[language.value]
}
return {
languageText
}
}

How can I set a ref to the value of an ajax call without triggering #update:modelValue in vue 3?

I have a checkbox that when clicked triggers an ajax call using the #update:modelValue syntax in the template. However whenever this page loads the ajax call gets called.
This is happening because when the setup() function runs I set the isPushNotificationChecked ref and then I update it in the onMounted function to be the response of a different ajax call.
Here is the code:
<template>
<ion-checkbox
slot="start"
v-model="isPushNotificationChecked"
#update:modelValue="updatePushNotifications"
></ion-checkbox>
</template>
<script>
import {
IonCheckbox,
} from "#ionic/vue";
import { defineComponent, ref, onMounted } from "vue";
import axios from "axios";
import useToast from "#/services/toast";
export default defineComponent({
name: "Settings",
components: {
IonCheckbox,
},
setup() {
const isPushNotificationChecked = ref(false);
onMounted(async () => {
const response = await axios.get("settings");
// Since I change the value here #update:modelValue in template triggers updatePushNotifications
isPushNotificationChecked.value = response.data.notifications_enabled;
});
// This gets triggered on page load when it shouldn't
const updatePushNotifications = async () => {
if (isPushNotificationChecked.value) {
axios.post("notifications/enable");
} else {
axios.post("notifications/disable");
}
useToast().success("Push notifications updated");
};
return {
isPushNotificationChecked,
updatePushNotifications,
};
},
});
</script>
How can I go about setting the ref value to be the response of an ajax call without removing the behaviour of clicking the checkbox and triggering the ajax call?
My solution was to instead use a watcher that is initialised in the onMounted() function and remove the #update:modelValue="updatePushNotifications":
<template>
<ion-checkbox
slot="start"
v-model="isPushNotificationChecked"
></ion-checkbox>
</template>
<script>
import {
IonCheckbox,
} from "#ionic/vue";
import { defineComponent, ref, onMounted } from "vue";
import axios from "axios";
import useToast from "#/services/toast";
export default defineComponent({
name: "Settings",
components: {
IonCheckbox,
},
setup() {
const isPushNotificationChecked = ref(false);
onMounted(async () => {
const response = await axios.get("settings");
isPushNotificationChecked.value = response.data.notifications_enabled;
// Watcher setup after ajax call.
watch(isPushNotificationChecked, (value) => {
if (value) {
axios.post("notifications/enable");
} else {
axios.post("notifications/disable");
}
useToast().success("Push notifications updated");
});
});
return {
isPushNotificationChecked
};
},
});
</script>

Using `useStore` API with vuex 4.x

Follow the official example to export your own useStore, and then use it in the component.
import { createStore, Store, useStore as baseUseStore } from 'vuex';
export const key: InjectionKey<Store<RootState>> = Symbol();
export function useStore() {
return baseUseStore(key);
}
use in the component
setup() {
const store = useStore();
const onClick = () => {
console.log(store)
store.dispatch('user/getUserInfo');
}
return {
onClick,
}
},
After running, store is undefined.
It can be obtained normally when I use it in the methods attribute
methods: {
login() {
this.$store.dispatch('user/getToken')
}
}
why? how to fix it
In that simplifying useStore usage tutorial, you still need to register the store and key in main.ts as they did. You will get undefined if you don't do this:
// main.ts
import { store, key } from './store'
const app = createApp({ ... })
// pass the injection key
app.use(store, key)
The reason is that baseUseStore(key) has no meaning until that's done.

Categories

Resources