VueUse: How to use the isSupported variable multiple times? - javascript

I want to make a fallback for a share button.
If useShareDialog isSupported = open ShareDialog
If useShareDialog !isSupported = copy to Clipboard
If useClipboard !isSupported = don't show the share button
VueUse has the useShare and useClipboard functions. But both use the same variable to check if the function is supported with the isSupported variable
How I can separate them?
Vue Component
<script setup>
import {
useClipboard, useShare
} from '#vueuse/core'
const { share, isSupported } = useShare({
title: 'Marcus Universe Portfolio',
text: 'Look at my awesome portfolio',
url: 'https://marcus-universe.de',
})
const {copy, copied, isSupported} = useClipboard({
source: 'https://marcus-universe.de'
})
function shareTrigger() {
if(isSupported) {
share()
} else {
copy()
}
}
</script>
<template>
<button
class="shareButtons"
#click="shareTrigger()"
v-if="isSupported">
{{ copied ? 'copied to clipboard' : 'Share' }}
</button>
</template>

You can rename variable:
const { share, isSupported: isSupportedShare } = useShare({...})
const {copy, copied, isSupported: isSupportedClipboard} = useClipboard({...})

Related

I have an ID of an object of an API, can i get and print that object?

I made this simple application. There is a homepage where i print movies with an API, and if I click the movie it opens a page with the selected movie info. In the info page I made another Api call. I customized the url so when you click on more info, it returns the id of the object that contains the movie's info. So I made a function that takes the id from the url and confronts it with the one of the call API. if they match, the function returns true. But how am i supposed to get and print the movie info with this data? What would you do? Here is the code:
<template>
<div>
<div v-for="info in movieInfo"
:key="info.id">
{{info.id}}
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
name: 'ViewComp',
data() {
return{
movieInfo: [],
}
},
mounted () {
axios
.get('https://api.themoviedb.org/3/movie/popular?api_key=###&language=it-IT&page=1&include_adult=false&region=IT')
.then(response => {
this.movieInfo = response.data.results
// console.log(response.data.results)
})
.catch(error => {
console.log(error)
this.errored = true
})
.finally(() => this.loading = false)
},
methods: {
confrontID(){
var url = window.location.href;
var idUrl = url.substring(url.lastIndexOf('/') + 1);
var idMovie = this.info.id;
if (idUrl === idMovie) {
return true;
}
}
}
}
</script>
<style scoped lang="scss">
/*Inserire style componente*/
</style>
You can get rid of the "return true" on as it will return true if they match. Then instead return the movie info associated with the idUrl
if (idUrl === idMovie) {
return idUrl;
}
Then use that to reference the movie

How to update a row with contenteditable in Vue?

I'm trying to figure out how to get the current changes in a 'contenteditable' and update it in the row that it was changed.
<tbody>
<!-- Loop through the list get the each data -->
<tr v-for="item in filteredList" :key="item">
<td v-for="field in fields" :key="field">
<p contenteditable="true" >{{ item[field] }}</p>
</td>
<button class="btn btn-info btn-lg" #click="UpdateRow(item)">Update</button>
<button class="btn btn-danger btn-lg" #click="DelteRow(item.id)">Delete</button>
</tr>
</tbody>
Then in the script, I want to essentially update the changes in 'UpdateRow':
setup (props) {
const sort = ref(false)
const updatedList = ref([])
const searchQuery = ref('')
// a function to sort the table
const sortTable = (col) => {
sort.value = true
// Use of _.sortBy() method
updatedList.value = sortBy(props.tableData, col)
}
const sortedList = computed(() => {
if (sort.value) {
return updatedList.value
} else {
return props.tableData
}
})
// Filter Search
const filteredList = computed(() => {
return sortedList.value.filter((product) => {
return (
product.recipient.toLowerCase().indexOf(searchQuery.value.toLowerCase()) != -1
)
})
})
const DelteRow = (rowId) => {
console.log(rowId)
fetch(`${import.meta.env.VITE_APP_API_URL}/subscriptions/${rowId}`, {
method: 'DELETE'
})
.then((response) => {
// Error handeling
if (!response.ok) {
throw new Error('Something went wrong')
} else {
// Alert pop-up
alert('Delete successfull')
console.log(response)
}
})
.then((result) => {
// Do something with the response
if (result === 'fail') {
throw new Error(result.message)
}
})
.catch((err) => {
alert(err)
})
}
const UpdateRow = (rowid) => {
fetch(`${import.meta.env.VITE_APP_API_URL}/subscriptions/${rowid.id}`, {
method: 'PUT',
body: JSON.stringify({
id: rowid.id,
date: rowid.date,
recipient: rowid.recipient,
invoice: rowid.invoice,
total_ex: Number(rowid.total_ex),
total_incl: Number(rowid.total_incl),
duration: rowid.duration
// id: 331,
// date: rowid.date,
// recipient: 'new R',
// invoice: 'inv500',
// total_ex: Number(500),
// total_incl: Number(6000),
// duration: 'Monthly'
})
})
}
return { sortedList, sortTable, searchQuery, filteredList, DelteRow, UpdateRow }
}
The commented lines work when I enter them manually:
// id: 331,
// date: rowid.date,
// recipient: 'new R',
// invoice: 'inv500',
// total_ex: Number(500),
// total_incl: Number(6000),
// duration: 'Monthly'
Each cell has content editable, I'm not sure how to update the changed event
The way these run-time js frontend frameworks work could be summarized as "content is the function of data". What I mean is the html renders the data that you send it. If you want the data to be updated when the user changes it, you need to explicitly tell it to do so. Some frameworks (like react) require you to setup 1-way data binding, so you have to explicitly define the data that is displayed in the template, as well as defining the event. Vue has added some syntactic sugar to abstract this through v-model to achieve 2-way binding. v-model works differently based on whichever input type you chose, since they have slightly different behaviour that needs to be handled differently. If you were to use a text input or a textarea with a v-model="item[field]", then your internal model would get updated and it would work. However, there is no v-model for non-input tags like h1 or p, so you need to setup the interaction in a 1-way databinding setup, meaning you have to define the content/value as well as the event to update the model when the html tag content changes.
have a look at this example:
<script setup>
import { ref } from 'vue'
const msg = ref('Hello World!')
</script>
<template>
<h1 contenteditable #input="({target})=>msg=target.innerHTML">{{ msg }}</h1>
<h2 contenteditable>{{ msg }}</h2>
<input v-model="msg">
</template>
If you change the h2 content, the model is not updated because vue is not tracking the changes. If you change through input or h1, the changes are tracked, which will also re-render the h2 and update its content.
TL;DR;
use this:
<p
contenteditable="true"
#input="({target})=>item[field]=target.innerHTML"
>{{ item[field] }}</p>

How to apply 'Markdown style for reply with InlineKeyboardButton?

How to apply { parse_mode: 'Markdown' } for reply with InlineKeyboardButton ?
const Telegraf = require("telegraf");
const Extra = require("telegraf/extra");
const Markup = require("telegraf/markup");
const keyboard = Markup.inlineKeyboard([
Markup.urlButton("❤️", "http://telegraf.js.org"),
Markup.callbackButton("Delete", "delete")
]);
const myReply = "Hello *mate*, __where are you ?__"
bot.on("message", ctx =>
ctx.telegram.sendMessage(ctx.chat.id, myReply, Extra.markup(keyboard))
);
Is there any option to add markdown style for message with InlineKeyboardButton ?
Telegraf 4
According to Telegraf 4.0 changelog, Extra is removed entirely.
If you have an inline-keyboard in a simple ctx.reply() (see the example), just use .replyWithHTML() or .replyWithMarkdown() or .replyWithMarkdownV2() instead of .reply().
ctx.replyWithMarkdownV2(
'*formatted* text',
Markup.inlineKeyboard([
Markup.button.callback('Coke', 'Coke'),
Markup.button.callback('Dr Pepper', 'Dr Pepper'),
Markup.button.callback('Pepsi', 'Pepsi')
])
)
If you have a more complex situation, you can pass an object like below as the appropriate argument to the ctx.reply() or ctx.telegram.sendMessage() or bot.telegram.editMessageText() etc.:
const extraObject = {
parse_mode: 'HTML',
...Markup.inlineKeyboard([
Markup.button.callback('Coke', 'Coke'),
Markup.button.callback('Pepsi', 'Pepsi'),
]),
}
ctx.telegram.sendMessage(ctx.chat.id, 'My <b>formatted</b> reply', extraObject)
To add Markdown styling to your message, chain markdown() to Extra.markup(), like this:
const keyboard = Markup.inlineKeyboard([
Markup.urlButton("❤️", "http://telegraf.js.org"),
Markup.callbackButton("Delete", "delete")
]);
const myReply = "Hello *mate*, _where are you ?_"
bot.on("message", ctx => {
ctx.telegram.sendMessage(ctx.chat.id, myReply, Extra.markdown().markup(keyboard));
});

How to change v-model value from JS

I'm using Google autocomplete address form. I found example at google official web page. Everything is fine. Everything works! but it's native Javascript,
I have Vue application and I don't like how I change text input values from JS script. The idea is that when I change something in main input, JS event listener should change values for other inputs:
document.getElementById(addressType).value = val;
Problem is that I should use "document" to change values:
document.getElementById('street_number').value
I would like to have something like tat:
<input type="text" v-model="input.address" ref="addressRef">
And to read values:
export default {
data() {
return {
input: {
address: "",
...
}
};
},
methods: {
test() {
console.log(this.input.address);
console.log(this.$refs.addressRef);
}
}
So the question is:
How to set the value from JS code to update binding values? Right now values are null because I use "getElementById("id").value = val"
You can emit input event afterwards which v-model relies on for updating its value:
let el = document.getElementById("id");
el.value = val;
el.dispatchEvent(new Event('input'));
In action:
Vue.config.devtools = false
const app = new Vue({
el: '#app',
data: {
message: null
},
methods: {
updateBinding() {
let el = document.getElementById("input");
el.value = 'Hello!';
el.dispatchEvent(new Event('input'));
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
<button #click="updateBinding">Click me </button><br>
<input id="input" v-model="message" placeholder="edit me">
<p>Message is: {{ message }}</p>
</div>

Vue.js + Require.js extending parent

I'm new to Vue.js but trying to get to grips with it. So far it has gone well and I've got quite far but I am stuck extending a parents template.
I am trying to make dashboard widgets that extend a default widget layout (in Boostrap). Please note that the below code is using Vue, Require, Underscore & Axios.
Parent file - _Global.vue
<template>
<div class="panel panel-default">
<div class="panel-heading">
<b>{{ widgetTitle }}</b>
<div class="pull-right">
<a href="#" v-on:click="toggleMinimized"
v-bind:title="(isMinimized ? 'Show widget' : 'Hide widget')">
<i class="fa fa-fw" v-bind:class="isMinimized ? 'fa-plus' : 'fa-minus'"></i>
</a>
</div>
</div>
<div class="panel-body" v-if="!isMinimized">
<div class="text-center text-muted" v-if="!isLoaded">
<i class="fa fa-spin fa-circle-o-notch"></i><br />
</div>
<parent v-if="isLoaded">
<!-- parent content should appear here when loaded -->
</parent>
</div>
</div>
</template>
<script>
export default {
// setup our widget props
props: {
'minimized': {
'default': false,
'required': false,
'type': Boolean
}
},
// define our data
data: function () {
return {
widgetTitle: 'Set widget title in data',
isLoaded: false,
isMinimized: this.$props.minimized
}
},
// when vue is mounted, open our widget
mounted: function () {
if(!this.isMinimized) {
this.opened();
}
},
// define our methods
methods: {
// store our widget state to database
storeWidgetState: function () {
// set our data to send
let data = {
'action' : 'toggleWidget',
'widget' : this.$options._componentTag,
'state' : !this.isMinimized
};
// post our data to our endpoint
axios.post(axios.endpoint, data);
},
// toggle our minimized data
toggleMinimized: function (e) {
// prevent default
e.preventDefault();
// toggle our minimized state
this.isMinimized = !this.isMinimized;
// trigger opened if we aren't minimized
if(!this.isMinimized) this.opened();
// save our widget state to database
this.storeWidgetState();
},
// triggered when opened from being minimized
opened: function () {
console.log('opened() method is where all widget logic should be placed');
}
}
}
</script>
Child file - Example.vue
Should extend _Global.vue using mixins and then display content within .panel-body
<template>
<div>
I want this content to appear inside the .panel-body div
{{ content }}
<img v-bind:src="image.src" v-bind:alt="image.alt"
v-if="image.src" class="img-responsive" style="margin: 0 auto" />
</div>
</template>
<script>
// import our widgets globals
import Global from './_Global.vue'
export default {
components: {
'parent': {
// what can I possibly put here??
}
},
// use our global mixin for all widgets
mixins: [Global],
// setup our methods for this widget
methods: {
opened: _.debounce(function () {
// make sure this can only be opened once
if(this.hasBeenOpened) return;
this.hasBeenOpened = true;
// temporarily allow axios to make external requests
let axiosHeaders = axios.defaults.headers.common;
let vm = this;
axios.defaults.headers.common = {};
axios.get('https://yesno.wtf/api')
.then(function (res) {
// set our content
vm.content = null;
// set our image content
vm.image.src = res.data.image;
vm.image.alt = res.data.answer;
})
.catch(function (err) {
// set our error text
vm.content = String(err);
})
.then(function () {
// this will always hit..
vm.isLoaded = true;
});
// restore our axios headers for security
axios.defaults.headers.common = axiosHeaders;
}, 300)
},
// additional data
data: function () {
return {
// set our widgets title
widgetTitle: 'Test title',
// logic for the specific widget
hasBeenOpened: false,
content: 'Loaded and ready to go...',
image: {
src: false,
alt: null
}
};
},
}
</script>
Currently my parent template is just completely overwriting my child view. The only way I can get it to work is by explicitly defining the template parameter inside components -> parent: {} but I don't want to have to do that...?
Ok, thanks to Gerardo Rosciano for pointing me the in right direction. I've used to slots to come up with an eventual solution. We then access parent methods and data attributes just to get everything working as it should.
Example.vue - our example widget
<template>
<div>
<widget-wrapper>
<span slot="header">Example widget</span>
<div slot="content">
<img v-bind:src="image.src" v-bind:alt="image.alt"
v-if="image.src" class="img-responsive" style="margin: 0 auto" />
{{ content }}
</div>
</widget-wrapper>
</div>
</template>
<script>
// import our widgets globals
import WidgetWrapper from './_Widget.vue'
export default {
// setup our components
components: {
'widget-wrapper': WidgetWrapper
},
// set our elements props
props: {
'minimized': {
'type': Boolean,
'default': false,
'required': false
}
},
// setup our methods for this widget
methods: {
loadContent: _.debounce(function () {
// make sure this can only be opened once
if(this.hasBeenOpened) return;
this.hasBeenOpened = true;
// temporarily allow axios to make external requests
let axiosHeaders = axios.defaults.headers.common;
let vm = this;
axios.defaults.headers.common = {};
axios.get('https://yesno.wtf/api')
.then(function (res) {
// set our content
vm.content = null;
// set our image content
vm.image.src = res.data.image;
vm.image.alt = res.data.answer;
})
.catch(function (err) {
// set our error text
vm.content = String(err);
})
.then(function () {
// this will always hit..
vm.isLoaded = true;
});
// restore our axios headers for security
axios.defaults.headers.common = axiosHeaders;
}, 300)
},
// additional data
data: function () {
return {
// global param for parent
isLoaded: false,
// logic for the specific widget
hasBeenOpened: false,
content: 'Loaded and ready to go...',
image: {
src: false,
alt: null
}
};
},
}
</script>
_Widget.vue - our base widget that gets extended
<template>
<div class="panel panel-default">
<div class="panel-heading">
<b><slot name="header">Slot header title</slot></b>
<div class="pull-right">
<a href="#" v-on:click="toggleMinimized"
v-bind:title="(minimized ? 'Show widget' : 'Hide widget')">
<i class="fa fa-fw" v-bind:class="minimized ? 'fa-plus' : 'fa-minus'"></i>
</a>
</div>
</div>
<div class="panel-body" v-if="!minimized">
<div class="text-center text-muted" v-if="!isLoaded">
<i class="fa fa-spin fa-circle-o-notch"></i><br />
Loading...
</div>
<div v-else>
<slot name="content"></slot>
</div>
</div>
</div>
</template>
<script>
export default {
// get loaded state from our parent
computed: {
isLoaded: function () {
return this.$parent.isLoaded;
}
},
// set our data element
data: function () {
return {
minimized: false
}
},
// when the widget is mounted, trigger open state
mounted: function () {
this.minimized = this.$parent.minimized;
if(!this.minimized) this.opened();
},
// methods to manipulate our widget
methods: {
// save our widget state to database
storeWidgetState: function () {
// set our data to send
let data = {
'action' : 'toggleWidget',
'widget' : this.$parent.$options._componentTag,
'state' : !this.minimized
};
// post this data to our endpoint
axios.post(axios.endpoint, data);
},
// toggle our minimized state
toggleMinimized: function (e) {
// prevent default
e.preventDefault();
// toggle our minimized state
this.minimized = !this.minimized;
// trigger opened if we aren't minimized
if(!this.minimized) this.opened();
// save our widget state to database
this.storeWidgetState();
},
// when widget is opened, load content
opened: function () {
// make sure we have a valid loadContent method
if(typeof this.$parent.loadContent === "function") {
this.$parent.loadContent();
} else {
console.log('You need to define a loadContent() method on the widget');
}
}
}
}
</script>

Categories

Resources