refs nonexistent in vuejs - vue.js

I want to trigger a button click programmatically in vuejs with a javascript method and I have the following line to reference it via the ref tag. below is my javascript
this.$refs.action.click();
Below is the html for the button
<button v-show="false" ref="action" type="button" data-toggle="modal" data-target="#MonitorModal" />
Is there a reason this isn't working? I believe it's all declared fine and when I run a console.log on this.$refs I see the action as anfield, but when I try to reference it, I get undefined

the elements are only available after the initial mount of the component
if you are using vue 2 try running your code on mounted life cycle hook.
mounted() {
this.$refs.action.click();
}
in vue 3 use onMounted life cycle hook.
const action = ref()
onMounted(()=>{
action.value.click()
}

Related

How add simple Jquery and <script> in VueJS?

I has simple <script> connect and jquery on page. Here is example: https://codepen.io/TidioSupport/pen/WNePeao
How i can add it correctly to my Vue component?
Because when i try add it, i received: Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed. or component not loading.
Hope for your help, thanks!
You should add it in the head of the html where you are calling your vue app
In your mounted lifecycle of Vuejs, you can append the script and then use its function.
Your variables for those scripts can be accessible by window global object.
mounted() {
let chatScript = document.createElement('script')
chatScript.setAttribute('src', 'https://code.tidio.co/fouwfr0cnygz4sj8kttyv0cz1rpaayva.js')
document.head.appendChild(chatScript)
}

How do we call a function within the html file of vuejs defined in the javascript file of vuejs without creating a button in the html file?

I pretty new to vuejs and am building a vuejs project. One of the tasks I am stuck at is, that I want to call a function written in the javascript part of vuejs from the html part of vuejs without creating any buttons or textboxes. I want to call this function as soon as my app starts. How do I achieve this? When I use mounted (vue lifecycle hook), the page it redirects to keeps refreshing. would appreciate some leads on this.
For example, I have a code:
<template>
<h1>Hello World!</h1>
<!--I WANT TO CALL THE auth0login function here. How do I do that without creating a button/text field,etc -->
</template>
<script>
export default {
data: () => ({
return : {
clientID: process.env.example
}
}),
methods:{
auth0login(){
console.log('logging in via Auth0!');
Store.dispatch('login');
}
}
}
</script>
I want to call the auth0login function defined in the script part in the html part above in order to execute the functionalities of the auth0login function. I want to do this without creating any buttons in the html file and simply just execute the auth0login function when the app launches.
How do I do this?
You need to call auth0login() only when you're not already logged I guess.
I think the reason is after user already logged in, they go back to the initial page, and the function in mounted() hook run again. Thats why they keep get redirect to login page. This not happen when you insert the button, because the button require user to click at it.
To fix this, you need to define a vuex state to store whether user has logged in or not, and in mounted() hook, just called it when they not login yet.
So. Instead of
mounted: function() { console.log('logging in via Auth0!'); this.auth0login() } }
Add a check login state
mounted() {
if(!this.$store.state.userLoggin) // here i define userLoggin and vuex state, you should update it to true whenever user successfully login
{ console.log('logging in via Auth0!'); this.auth0login() //only call it when user not loggin
}
}
And remember to update your vuex state.userLoggin when user successfully login in the auth0login() function

How to use events of vue-tel-input?

I've installed vue-tel-input component and included it. I want to use the validate event tha's found in a link! but I can't. How to use it in the compoennt?
The events are regular vue component events.
You can listen for these events as outlined here in the vue docs.
https://v2.vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events
For example, to use the validate event you would add a listener to the vue-tel-input component.
The listener will automatically pass the arguments to your method.
// In your template
<vue-tel-input
v-model="yourModel"
#validate="yourValidationMethod"
/>
// In your component methods
yourValidationMethod: function ({ number, isValid, country }) {
// Do stuff with the arguments passed by the vue-tel-input component
},
Have your tried with Info from their page ?
In main.js
import Vue from 'vue'
import VueTelInput from 'vue-tel-input'
Vue.use(VueTelInput)
and then use it as component
<template>
<vue-tel-input v-model="phone"></vue-tel-input>
<template>

How would a WebTorrent VueJS component could be build?

Hy there. Given webtorrent.io I would like to build a VueJS component that shows loading magnet files, and status and also when downloads finishes triggers players.
Is the Vuex Store a good place to keep a list of active download queues and a stream o data?
All that is possible with webtorrent.
var WebTorrent = require('webtorrent')
var client = new WebTorrent()
var magnetURI = 'magnet: ...'
client.add(magnetURI, { path: '/path/to/folder' }, function (torrent) {
torrent.on('done', function () {
console.log('torrent download finished')
})
})
How could I structure that architecture/pattern with VueJS? Any insights, apreciated
Thanks!
I will answer cause I found a solution. Then if the community wants this to be deleted, its all right.
Basically what I did is wait for a Component to be mounted.
Inside AComponent.Vue
<template>
<keep-alive>
<!-- HTML binding webtorrent client data -->
</keep-alive>
</template>
<script>
export default {
mounted() {
var client = WebTorrent()
}
}
</script>
Why this achieve what I was looking for ? :
keep alive keep that parts of the DOM alive, when i render another template and come back to this one (as if the download queue is in a widget, modal, or another view that needs to keep alive).
mounted, its part of the component lifecycle hooks (https://v2.vuejs.org/v2/guide/instance.html#Lifecycle-Diagram), and happens once the DOM has been maniuplated, window exists (needed by WebTorrent), and the component has been rendered.

when to initialize vue and vuex state

Recently I design web that user was separated into "user"/"admin" two roles to login.
Different role would login same page but see the different buttons and functions.
MainPage.vue is the container so I call ajax "/init" to get user info and then commit to Vuex store.
Then Content.vue is the child page inside MainPage.vue. It would show different buttons by $store.state.user message.
However, I would like to call different api in mounted stage inside Content.vue according to user's role.
But the role would not be prepared which is commited by ajax called "/init" at this stage.
The overall flow is
// MainContent.vue
beforeCreate: async function () {
await axios.post('/init').then(response => {
if(response && response.data && response.data.data){
this.$store.commit("login", response.data.data)
}
})
}
// Content.vue
mounted: async function() {
try {
console.log(this.$store, this.$store.state.user, this.$store.getters.isAdmin)
// no value here
}
I have check the vue component lifecycle and saw beforeCreate of parent would be called before mounted of child.
Would lifecycle methods call in order even they are async function?
How should I solve this problem?
Thanks
You could delay the initialization of the Content component until the user state becomes available in Vuex by attaching a v-if directive to the Content component. Just make sure to initialize user with null in the Vuex state.
<!-- MainPage.vue -->
<template>
<Content v-if="$store.state.user" />
</template>
Now this.$store.state.user and everything that depend on it should be available from Content component's mounted lifecycle hook.
Your component lifecycle will not be a dependable way to handle this case since you're using an async call to fetch the user data. I would suggest displaying a loading state overlay and using mapGetters to access the store. This will provide a reactive mechanism for you to know when the user data is available. Below is a general idea for a single file component:
computed: {
...mapGetters({
getLoggedInUser: 'GET_LOGGED_IN_USER',
getIsUserAdmin: 'GET_IS_USER_ADMIN',
})
}
....
<template>
<content-overlay v-if="!getLoggedInUser">
Loading...
</content-overlay>
....
<button v-if="getIsUserAdmin">Admin Button</button>
<button v-if="!getIsUserAdmin">Regular User Button</button>
</template>