How to call a function in setup() to a function in methods? - javascript

I have function in setup() named onRquest, I want to call that function in methods after execution of an action(deleting row), which gonna refresh the table. Please check the code segment for better understanding:
export default {
setup() {
function onRequest(props) {
}
onMounted(() => {
onRequest({
pagination: pagination.value,
filter: undefined,
})
})
return {
onRequest
}
},
methods: {
deleteBranch(branch_id) {
this.$q.dialog({
title: 'Confirm',
message: 'Would you like to Delete Branch#' + branch_id + '?',
cancel: true,
persistent: true
}).onOk(() => {
this.$axios.delete('https://api.bdshsystem.com/api/v1/branch/' +
branch_id).then(response => {
this.$q.notify({
type: 'positive',
timeout: 500,
position: 'top',
message: 'Branch Deleted Successfully !'
})
I want to put function onRequest Here
}).catch((error) => {
this.$q.notify({
type: 'negative',
position: 'top',
timeout: 500,
message: 'Form submission Failed !'
})
})
}).onOk(() => {
// console.log('>>>> second OK catcher')
}).onCancel(() => {
// console.log('>>>> Cancel')
}).onDismiss(() => {
// console.log('I am triggered on both OK and Cancel')
})
},
},
}

Insted of passing you method inline i.e. the "setup()" method, directly in export default. define it outside and pass its reference to export default then you can call setup() directly in whatever method you want
function setup(){
//some code
}
export default {"setup":setup,
"yourOtherMethod":function yourOtherMethod(){
//your other method code here
}}

Related

How to get a value from a subcribe

I would like to know how I can get a value that I have in a subscribe pass it to a variable and be able to manipulate it example
getNumber: number;
I want in the same .ts to use that variable getNumber
someMethodTwo() {
this.someMethod().subscribe(data =>
Swal.fire({
position: 'top-end',
icon: 'success',
title: 'it's is the variable '+ getNumber ,
showConfirmButton: false,
timer: 1500
})
}
someMethodOne() {
this.someMethod().subscribe(data =>
this.getNumber= data);
}
if someMethod returns an observable you can use
.pipe(map(value => {
// manipulate value here and return it
}
)).subscribe((value) => {
this.yourlocalvaribale = value
)

Child is not updated when boolean prop is changed

I have the following components:
Parent:
<template>
<Child path="instance.json"
v-bind:authenticated="authenticated"
v-bind:authenticator="authenticator"
/>
</template>
<script>
import { getAuthenticator } from '../auth';
export default {
data() {
return {
authenticated: false,
authenticator: null
};
},
beforeMount: async function () {
this.authenticator = getAuthenticator()
this.checkAccess();
},
methods: {
checkAccess() {
this.authenticated = this.authenticator.isAuthenticated();
},
async login() {
this.checkAccess();
await this.authenticator.signIn();
this.checkAccess();
}
}
};
</script>
Child:
<template>
<div id="swagger-ui"></div>
</template>
<script>
import swagger from "swagger-ui-dist";
import "swagger-ui-dist/swagger-ui.css";
export default {
props: ["path", "authenticated", "authenticator"],
mounted: async function() {
if (this.authenticated) {
let token = (await this.authenticator.getToken()).accessToken;
const ui = swagger.SwaggerUIBundle({
url: this.path,
dom_id: "#swagger-ui",
onComplete: function() {
ui.preauthorizeApiKey("token", token);
}
});
} else {
const ui = swagger.SwaggerUIBundle({
url: this.path,
dom_id: "#swagger-ui"
});
}
}
};
</script>
In the parent component, when the login method is called, the authenticated variable changes to true. Since authenticated is passed as a prop to the Child component, I'd expect the Child to be refreshed whenever authenticated is changed. However, the Child does not refresh.
I think that the problem might be caused by the fact that I am not using authenticated in the template of the child at all. Instead, I'm using it only in the mounted hook. In my case, I have no use for authenticated in the template.
I tried two solutions:
calling this.$forceUpdate() in the login method of Parent - that didn't work at all (nothing changed)
Adding :key to the Child, and changing the key each time the login is called - this works, however, it's a bit hacky. I'd like to understand how to do that properly.
what you need is to use a watcher.
Actually, your code is only run once (when de component is mounted), not at each prop change.
<template>
<div id="swagger-ui"></div>
</template>
<script>
import swagger from 'swagger-ui-dist';
import 'swagger-ui-dist/swagger-ui.css';
export default {
props: {
path: {
type: String,
default: '',
},
authenticated: {
type: Boolean,
default: false,
},
authenticator: {
type: Object,
default: () => {},
},
},
watch: {
async authenticated(newValue) {
await this.updateSwagger(newValue);
},
},
async mounted() {
await this.updateSwagger(this.authenticated);
}
methods: {
async updateSwagger(authenticated) {
if (authenticated) {
const token = (await this.authenticator.getToken()).accessToken;
const ui = swagger.SwaggerUIBundle({
url: this.path,
dom_id: '#swagger-ui',
onComplete: function () {
ui.preauthorizeApiKey('token', token);
},
});
} else {
const ui = swagger.SwaggerUIBundle({
url: this.path,
dom_id: '#swagger-ui',
});
}
},
},
};
</script>
It's fine that you're not using it in the template, the issue is that you only check authenticated in the child's mounted hook, which only runs once (and is false at that time).
You should use a watch to track changes to the authenticated prop instead of mounted:
watch: {
authenticated: {
handler(newValue, oldValue) {
this.setUi();
},
immediate: true // Run the watch when `authenticated` is first set, too
}
}
That will call a setUi method every time authenticated changes:
methods: {
async setUi() {
if (this.authenticated) {
let token = (await this.authenticator.getToken()).accessToken;
const ui = swagger.SwaggerUIBundle({
url: this.path,
dom_id: "#swagger-ui",
onComplete: function() {
ui.preauthorizeApiKey("token", token);
}
});
} else {
const ui = swagger.SwaggerUIBundle({
url: this.path,
dom_id: "#swagger-ui"
});
}
}
}

How to apply iterations condition for function in K6

I want to execute logout function for one time and dropDown function for multiple iterations. Which changes shoul I need in below code.
executors: {
logout: {
type: 'per-vu-iterations',
exec: 'logout',
vus: 1,
iterations: 1,
startTime: '30s',
maxDuration: '1m',
tags: { my_tag: 'LOGOUT'},
},
}};
export function logout() {
group('Logout API', () => {
loginFunctions.logout_api();
})
}
export function dropDown() {
group('Drop Down API', () => {
loginFunctions.dropDown_api();
})
}
export default function () {
logout();
dropDown();
}
Also without default function it's not working. getting executor default: function 'default' not found in exports this error
Not sure where you saw executors, that was the old name of the option, before #1007 was merged and released. The new and correct name is scenarios: https://k6.io/docs/using-k6/scenarios
So, to answer your question, the code should look somewhat like this:
import http from 'k6/http';
import { sleep } from 'k6';
export let options = {
scenarios: {
logout: {
executor: 'per-vu-iterations',
exec: 'logout',
vus: 1, iterations: 1,
maxDuration: '1m',
tags: { my_tag: 'LOGOUT' },
},
dropDown: {
executor: 'per-vu-iterations',
exec: 'dropDown',
vus: 10, iterations: 10, // or whatever
maxDuration: '1m',
tags: { my_tag: 'LOGOUT' },
},
}
};
export function logout() {
console.log("logout()");
sleep(1);
// ...
}
export function dropDown() {
console.log("dropDown()");
sleep(1);
// ...
}
Though, depending on your use case, the best place for the logout() code might actually be in the teardown() lifecycle function? See https://k6.io/docs/using-k6/test-life-cycle for more details

Vue returning data objects from axios call to controller

I'm using vue in laravel and trying to get a controller function that I'm hitting to return the data so that I can use it in the data() section of my vue template.
I know the controller function returns what I need, but I'm not so sure how I need to handle the return/response in the axios call in order to start placing the data into the data() function in vue
Blade/Vue template
import moment from 'moment'
export default {
name: 'calendar',
data () {
return {
events: [
{
title: 'test',
allDay: true,
start: '2019-08-17',
},
],
config: {
defaultView: 'month',
eventRender: function(event, element) {
console.log(event)
}
},
}
},
created() {
this.fetchTasks();
},
methods: {
fetchTasks() {
axios.get('/landing/tasks' )
.then((response) => {
// handle success
this.assetOptions = response.data;
})
.catch(function (error) {
// handle error
console.log(error);
})
.finally(function () {
});
}
}
}
Route
Route::get('/landing/tasks', 'landingController#getTasks')
->name('landing/tasks');
Controller
public function getTasks()
{
$getTask = Task::getTaskForLanding();
$result = array();
foreach($getTask as $id => $task){
$result[$task->taskt_id][] = $task;
}
}
If you are certain that the Controller returns what you need, the only thing you are missing is declaration of assetOptions. To be able to assign response.data to assetOptions later on, you have to declare it in the data function first.
data() {
return {
...
assetOptions = []; // assuming you are expecting an array
...
};
}
Once that is done, you are all set.

vue mapGetters not getting on time

I'm using vuex to manage the state in my application and doing one way binding with my form.
<script>
import { mapGetters } from 'vuex'
import store from 'vuex-store'
import DataWidget from '../../../../uiComponents/widget'
export default {
data () {
return {
isEdit: false,
msg: {
id: 0,
content: '',
isEnabled: false
}
}
},
components: {
DataWidget
},
computed: mapGetters({
messageId: 'messageId',
messageContent: 'messageContent',
isMessageEnabled: 'isMessageEnabled',
isMessageValid: 'isMessageValid'
}),
methods: {
onSave () {
store.dispatch('saveMessage', this.msg, { root: true })
if (this.isMessageValid) {
this.isEdit = !this.isEdit
}
}
},
created () {
this.msg.id = this.messageId
this.msg.content = this.messageContent
this.msg.isEnabled = this.isMessageEnabled
}
}
</script>
<b-form-textarea id="content" v-model="msg.content" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>
On load, the values on created() are not binded until I perform an action on the page or refresh the page.
I have tried mounted () hooked same thing.
My Vuex store (Message Module) looks like this:
const state = {
messageId: 0,
messageContent: '',
isMessageEnabled: false,
isMessageValid: true
}
const getters = {
messageId: state => state.messageId,
messageContent: state => state.messageContent,
isMessageEnabled: state => state.isMessageEnabled,
isMessageValid: state => state.isMessageValid
}
const actions = {
getMessage ({commit, rootGetters}) {
api.fetch('api/Preference/Message', rootGetters.token)
.then((data) => {
commit(types.MESSAGE_LOAD, data)
})
}
}
const mutations = {
[types.MESSAGE_LOAD] (state, payload) {
state.messageId = payload ? payload.id : 0
state.messageContent = payload ? payload.content : ''
state.isMessageEnabled = payload ? payload.enabled : false
}
}
export default {
state,
getters,
actions,
mutations
}
and I have a global action (action.js) the gets multiple data:
export const loadSetting = ({ commit, rootGetters }) => {
api.fetchAsync('api/Preference/all', rootGetters.token)
.then((data) => {
commit(types.MESSAGE_LOAD, data.message)
commit(types.HELPDESK_LOAD, data.helpDesk)
commit(types.VOLUME_LOAD, data.volumes)
commit(types.DOWNLOAD_LOAD, data.downloadService)
})
}
My api call:
async fetchAsync (url, token = '') {
let data = await axios.get(HOST + url, {
headers: {
'Authorization': 'bearer ' + token
}
})
return data
}
The problem is your'e calling an async method in Vuex but in the created method, you're treating it like a sync operation and expect to get a value.
You need to use the computed properties you created since they are reactive and will update on every change. In order to make the computed writeable change it to be like this:
computed: {
...mapGetters({
messageId: 'messageId',
isMessageEnabled: 'isMessageEnabled',
isMessageValid: 'isMessageValid'
}),
messageContent(){
get () {
return this.$store.getters.messageContent
},
set (value) {
//this is just an example, you can do other things here
this.$store.commit('updateMessage', value)
}
}
}
And change the html to use messageContent:
<b-form-textarea id="content" v-model="messageContent" :rows="3" required aria-required="true" maxlength="250"></b-form-textarea>
For more info refer to this: https://vuex.vuejs.org/en/forms.html

Categories