I run the Fetch hook from the example from the official site - vue.js

I run the Fetch hook from the example from the official site. "nuxt": "^ 2.14.7"
Gives an error message
fetch.client.js:109 Error in fetch(): TypeError: Cannot read property '$get' of undefined
at _callee$ (index.js?!./node_modules/vue-loader/lib/index.js?!./pages/Video.vue?vue&type=script&lang=js&:74)
at tryCatch (runtime.js:63)
at Generator.invoke [as _invoke] (runtime.js:293)
at Generator.eval [as next] (runtime.js:118)
at asyncGeneratorStep (asyncToGenerator.js:5)
at _next (asyncToGenerator.js:27)
at eval (asyncToGenerator.js:34)
at new Promise (<anonymous>)
at eval (asyncToGenerator.js:23)
at VueComponent.fetch (index.js?!./node_modules/vue-loader/lib/index.js?!./pages/Video.vue?vue&type=script&lang=js&:88)
My code
<script>
export default {
layout: 'videoLayout',
name: "Video",
async fetch () {
this.posts = await this.$http.$get('https://jsonplaceholder.typicode.com/posts')
.then(posts => posts.slice(0, 20))
console.log(this.posts)
},
fetchOnServer: false,
data: () => ({
posts: [],
videos: [
{
color: 'red lighten-2',
icon: 'mdi-star',
id: 1,
title: '22.10.2020 Блага Вість Черкаси',
videoId: 'GpgmeaSQ2bc',
},
{
color: 'purple darken-1',
icon: 'mdi-book-variant',
id: 2,
title: '22.10.2020 Блага Вість Черкаси',
videoId: '25yGGiYARbc',
},
{
color: 'green lighten-1',
icon: 'mdi-airballoon',
id: 3,
title: '22.10.2020 Блага Вість Черкаси',
videoId: 'mZbHFWWd6fg',
},
{
color: 'indigo',
icon: 'mdi-buffer',
id: 4,
title: '22.10.2020 Блага Вість Черкаси',
videoId: 'mZbHFWWd6fg',
},
],
}),
methods: {
refresh() {
this.$fetch()
},
ready (event) {
this.player = event.target
},
method (url) {
this.videoId = this.$youtube.getIdFromURL(url)
this.startTime = this.$youtube.getTimeFromURL(url)
}
}
}
</script>

I think you may need to install http module first like so:
npm install #nuxt/http
Then add the following to nuxt.config.js:
export default {
modules: [
'#nuxt/http',
],
http: {
// configure any options like
// baseURL: "https://jsonplaceholder.typicode.com"
}
}
Then you can make the calls as you were in your code:
async fetch () {
this.posts = await this.$http.$get('/posts').then(posts => posts.slice(0, 20))
}

Related

Unable to use Handler with vue-quill-editor

What I'm trying to do?
Use a Handler that allow me insert an image by URL, the reason for this is to not use too much space in the Database.
What version of Vue I'm using?
Vue 2
What is not working?
When I add the handler, quill toolbar doesn't identify my custom toolbar, and it adds all the options, the console is throwing me the next error: "[Vue warn]: Error in data(): "ReferenceError: showImageUI is not defined".
Also "this.quill.insertEmbed()" is not working, the console threw me this: "Uncaught ReferenceError: Quill is not defined" (this pass when I change the Handler Image value, I'll let the second option at the final)
<template>
<div class="addBlog">
<h1>Add New Blog</h1>
<quill-editor v-model="content" :options="editorOptions" ref="myQuillEditor"/>
</div>
</template>
<script>
import 'quill/dist/quill.snow.css';
import { Quill, quillEditor } from 'vue-quill-editor';
export default {
name: 'AddBlog',
components: {
quillEditor
},
data: () => ({
title: '',
category: '',
content: '',
editorOptions: {
theme: 'snow',
debug: 'info',
placeholder: 'Type your post...',
readOnly: true,
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline', 'strike'],
['link', 'image', 'video']
],
handlers: { image: showImageUI }
}
}
},
// debug: 'info',
// placeholder: 'Type your post...',
// readOnly: true,
// theme: 'snow'
// },
delta: undefined
}),
methods: {
showImageUI() {
var range = this.quill.getSelection();
var value = prompt('please copy paste the image url here.');
if(value){
this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
}
}
},
watch: {
content() {
this.delta = this.$refs.myQuillEditor.quill.getContents();
}
}
};
</script>
And here I let you the code(the second option) where I used directly the function into the handler:
editorOptions: {
theme: 'snow',
debug: 'info',
placeholder: 'Type your post...',
readOnly: true,
modules: {
toolbar: {
container: [
['bold', 'italic', 'underline', 'strike'],
['link', 'image', 'video']
],
handlers: { image: function imageHandler() {
var range = this.quill.getSelection();
var value = prompt('please copy paste the image url here.');
if(value){
this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
}} }
}
}
},

Error in mounted hook (Promise/async): "TypeError: Cannot read property 'length' of undefined"

I have created a project with Vue. I'm trying to show some data through a chart using the ChartJs library, to capture the information I use axios. I've been getting this error since the beginning but I don't know what I'm missing, any idea?
async created() {
const { data } = await axios.get("https://covid19.mathdro.id/api/confirmed");
var c=0
for(var i=0;i<1000;i++){
if(data[i].countryRegion=="India"){
if (data[i].provinceState in this.labels){
continue
}
else{
this.labels.push(data[i].provinceState)
this.confirmed.push(data[i].confirmed)
c=c+1
if(c==28){
break
}
}
}
}
console.log(this.labels)
}
In the error message it also mentions this function which is in the LineChart.vue file
<template>
<canvas ref="chartLine" width="900px" height="250px"></canvas>
</template>
<script>
import Chart from 'chart.js';
export default {
props: {
label: {
type: Array
},
chartData: {
type: Array
},
},
async mounted() {
await new Chart(this.$refs.myChart, {
type: 'line',
data: {
labels: this.label,
datasets: [
{
label: 'CASES',
borderColor: 'rgba(245, 229, 27, 1)',
backgroundColor: 'rgba(255, 236, 139,0.2)',
data: this.chartData,
}
]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
}
}
</script>

Apexchats.js axios gives me undefined with Vue

I am trying to get data from server using vue and apexcharts, but even after I called data with axios, it gives me undefined..
What have I missed?
template
<apexchart
ref="chart1"
width="100%"
:options="chartOptions" :series="series">
</apexchart>
data from url
{
"pageviews": 1313,
"new_users": 1014
}
script
export default {
data: function () {
return {
series: [],
chartOptions: {
chart: {
type: 'donut',
},
colors: ['#01cd49', '#007568'],
labels: ['new', 're'],
}
},
created: function () {
this.getByVisitor()
},
methods: {
getByVisitor() {
const url = 'url';
axios
.get(url)
.then(response => {
this.$refs.chart1.updateSeries([{
name: 'Sales',
data: response.data
}])
})
.catch(error => (this.byVisitor = error.data));
console.log(`---------------this.$refs.chart1`, this.$refs.chart1);
},
}
See Updating Vue Chart Data
There's no need to directly call the updateSeries() method on the chart component since it is able to react to changes in series. All you have to do is update your series data property
export default {
data: () => ({
series: [], // 👈 start with an empty array here
byVisitor: null, // 👈 you seem to have missed this one for your error data
chartOptions: {
chart: {
type: 'donut',
},
colors: ['#01cd49', '#007568'],
labels: ['new', 're'],
}
}),
created: function() {
this.getByVisitor()
},
methods: {
async getByVisitor() {
const url = 'url';
try {
const { data } = await axios.get(url)
// now update "series"
this.series = [{
name: "Sales",
data
}]
} catch (error) {
this.byVisitor = error.data
}
},
}
}

Vue PayPal implementation with vue-head, paypal not defined

I'm trying to add the paypal sdk via vue-head(https://www.npmjs.com/package/vue-head) in my component but I keep getting this error:
Error in mounted hook: "ReferenceError: paypal is not defined"
What am I doing wrong here? Is the SDK simply not loading before mounted?
Is there a better way to accomplish this? Does anyone have an example of their paypal implementation in vue? Any help would be greatly appreciated.
edit: Also if I include the script tag server side (rails) then try to access paypal in vue I see this error:
Could not find driver for framework: [object Object]
<template>
<div id="paypal-button" />
</template>
<script>
import { mapState as mapConfigState } from '../scripts/store/appConfig';
export default {
props: {
totalPrice: {
type: String,
required: true,
},
currency: {
type: String,
required: true,
'default': 'USD',
},
buttonStyle: {
type: Object,
required: false,
},
},
computed: {
...mapConfigState({
customer: state => state.customer,
}),
paypalEnvironment() {
return (this.customer.paypalTestingMode) ? 'sandbox' : 'production';
},
client() {
return {
sandbox: this.customer.paypalClientIdSandbox,
production: this.customer.paypalClientIdLIVE,
};
},
},
head: {
script() {
return [
{
type: 'text/javascript',
src: `https://www.paypal.com/sdk/js?client-id=${this.client[this.paypalEnvironment]}`,
},
];
},
},
mounted() {
const total = this.totalPrice;
const currency = this.currency;
paypal.Buttons.driver(
{
env: this.paypalEnvironment,
client: this.client,
style: this.buttonStyle,
createOrder(data, actions) {
return actions.order.create({
purchase_units: [
{
amount: {
value: total,
currency,
},
},
],
});
},
onApprove(data, actions) {
return actions.order.capture();
},
}, '#paypal-button'
);
},
};
</script>
edit2: I tried adding the script in my mounted hook like this:
let el = document.querySelector(`script[src="https://www.paypal.com/sdk/js?client-id=${this.client[this.paypalEnvironment]}"]`);
if (!el) {
const src = `https://www.paypal.com/sdk/js?client-id=${this.client[this.paypalEnvironment]}`;
el = document.createElement('script');
el.type = 'text/javascript';
el.async = true;
el.src = src;
document.head.appendChild(el);
}
I can see the script in the head tag in the dev console but paypal still is not defined.
For anyone else who is trying to implement PayPal in a Vue component:
<template>
<div id="paypal-button" />
</template>
<script>
export default {
mounted() {
function loadScript(url, callback) {
const el = document.querySelector(`script[src="${url}"]`);
if (!el) {
const s = document.createElement('script');
s.setAttribute('src', url); s.onload = callback;
document.head.insertBefore(s, document.head.firstElementChild);
}
}
loadScript('https://www.paypal.com/sdk/js?client-id=sb&currency=USD', () => {
paypal.Buttons({
// Set up the transaction
createOrder(data, actions) {
return actions.order.create({
purchase_units: [{
amount: {
value: '0.01',
},
}],
});
},
// Finalize the transaction
onApprove(data, actions) {
return actions.order.capture().then(details => {
// Show a success message to the buyer
alert(`Transaction completed by ${details.payer.name.given_name}`);
});
},
}).render('#paypal-button');
});
},
};
</script>
Alternatively you can use this: https://github.com/paypal/paypal-js

Vue JS if statement returns both outcomes

I am making a website with a login function. However, when you successfully log in, it tells you both that the login failed and that it succeeded. Here is the code that handles the login message:
log () {
const self = this
firebase.auth().signInWithEmailAndPassword(this.regname, this.passname).catch(function (error) {
console.log(error.code, error.message)
})
firebase.auth().onAuthStateChanged(function (user) {
const huser = !!user
if (huser === true) {
self.$router.push('/firstlogged')
self.$q.notify({
color: 'positive',
spinner: true,
timeout: 5000,
progress: true,
message: 'Login Success!',
actions: [
{ label: 'Dismiss', color: 'white', handler: () => { /* ... */ } }
]
})
} else if (huser === false) {
self.$q.notify({
timeout: 5000,
progress: true,
color: 'negative',
message: 'Login Failed, check your input',
actions: [
{ label: 'Dismiss', color: 'white', handler: () => { /* ... */ } }
]
})
}
})
},
Obviously, it should only send one of these messages. It does however work if you put in the wrong login details. Any fixes to this?