Custom directive data unable to pass to method in Vue 3 - vue.js

In my html I reference the directive: v-init:url="myurlhere"
data() {
return {
currentPage: 1,
url: '',
news: '',
}
},
directives: {
init: {
mounted(el, binding) {
console.log(binding.value);
this.iterateUrlContents(binding.value)
},
}
},
methods: {
iterateUrlContents(url) {
console.log('url: ' + url);
console.log(binding.value) shows the expected result, however when I call iterateUrlContents I get the following:
Unhandled error during execution of directive hook
Uncaught TypeError: Cannot read property 'iterateUrlContents' of
undefined
And I also find that if I try this.url = binding.value I get
Uncaught TypeError: Cannot set property 'url' of undefined
Why is binding.value undefined, and how can I pass this information to my method?

If you want to access the component instance you need to do it via binding.instance in Vue3.

Related

Cannot read properties of undefined (reading 'elements') at VueComponent.mounted vue-stripe

i've a vue app which uses stripe as payment but each time i refresh i get
Cannot read properties of undefined (reading 'elements')
this the error i get in my console
Error in mounted hook: "TypeError: Cannot read properties of undefined (reading 'elements')"
this is my script tag on how i call my stripe payment
<script>
export default {
data() {
return {
error: "",
stripe: null,
card: null
};
},
computed: {
...mapGetters([
"getCart",
])
},
mounted() {
this.stripe = Stripe("pk_test_51KGqWkHC");
let elements = this.stripe.elements();
this.card = elements.create("card");
this.card.mount(this.$refs.card);
},
methods: {
async onPurchase() {
try {
let token = stripe.createToken(this.card);
let response = axios.post("http://localhost:5000/api/pay", {
token: token,
totalPrice: this.getCartTotalPriceWithShipping,
cart: this.getCart,
estimatedDelivery: this.getEstimatedDelivery
});
if (response.success) {
// Do something like redirecting to the home page
this.$store.commit("clearCart");
this.$router.push("/");
}
} catch (err) {
console.log(err);
}
},
}
};
</script>
I use this in my nuxt js project and it works fine,
please what i'm i doing wrong in vue
this.stripe.elements();
returns undefined, probably this is not working:
Stripe("pk_test_51KGqWkHC");
check that the initialization string you are using is correct.
Otherwise, check the docs.
if its undefined, you can handle this error:
mounted() {
this.stripe = Stripe("pk_test_51KGqWkHC");
if(this.stripe.elements) {
let elements = this.stripe.elements();
this.card = elements.create("card");
this.card.mount(this.$refs.card);
}
},
But seeing your whole code, you have some inconsistencies:
Im not sure how you're supposed to access to Stripe(), if you don't have imported it. Maybe it's a module?
Stripe("pk_test_51KGqWkHC") -> this.$stripe("pk_test_51KGqWkHC")
Then in let token = stripe.createToken(this.card);
stripe doesn't exists in async onPurchase(), so how do you have access to it?
This should be this.stripe.createToken(this.card) or this.$stripe.createToken(this.card) if Stripe is injected on Vue.

NuxtJs append query param on every route navigation

I have a query string that I need to append to every route so that when I click a link it grabs the querystring and appends it to the URL. This way when I do something like to="route" it will automatically append my querystring to the URL.
I have go this working when I do a single click, however when I double click anything it blows up on me with the following error
"TypeError: First argument must be a string, Buffer, ArrayBuffer,
Array, or array-like object".
I also see this error in my console every time, just not on the page, so I imagine I am not doing something correctly.
In my default.vue page I have the following:
<script>
export default {
components: {
// all the components I am using on this page
},
data: () => {
return {
landingRoute: '',
}
},
fetch() {
if (this.isEmpty(this.$route.query)) {
const landingKey = this.landingRoute
this.$router.push({
name: this.$router.name,
query: { info: landingKey },
})
}
},
watch: {
'$route.query': '$fetch',
},
beforeMount() {
this.landingRoute = this.$route.query.info
},
methods: {
isEmpty(json) {
return Object.keys(json).length === 0
},
},
}
</script>
The error happens in the client.js the stack trace looks like this....
"TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object".
at fromObject (index.js?b639:139)
at from (index.js?b639:137)
at Function.Buffer.from (index.js?b639:149)
at eval (sessionLog.js?d88f:14)
at promisfiy (utils.js?ebed:291)
at middlewareSeries (utils.jseed:291)
at Vue.callMiddlewear (client.js?06a0:267)
at Vue._calle6$ (client.js05a0:267)
at tryCatch (runtime.js?96cf:63)
at Generator.invoke [as _invoke] (runtime.js?96cf:294)
Here is my sandbox
https://codesandbox.io/s/nuxtjs-vuetify-forked-wrs2s?file=/layouts/default.vue

[Vue warn]: Error in callback for watcher TypeError: Cannot use 'in' operator to search for

I have this data and computed method is also there
data(){
return {
pdf_path:'',
medical: {
name: '',
designation: '',
account_no: '',
staff_no: '',
},
}
},
computed:{
getFilePath: function () {
if(this.pdf_path!=""){
return '../../../../storage/' + this.pdf_path + '?t=' + new Date().getTime();
}
}
},
async mounted(){
const header = {
'Authorization': 'Bearer ' + this.getLoginUserData,
};
await axios.get('/api/backend/users',{headers:header}).then((responseUser) => {
this.medical.name = responseUser.data.name;
this.medical.account_no = responseUser.data.account_no;
this.medical.staff_no = responseUser.data.userUniqueId;
this.medical.designation = responseUser.data.role_id;
return axios.get(`/api/backend/dependent-list/${this.userId}`,{headers:header});
});
},
In the template i'm using the computed property:
<iframe :src="`${getFilePath}`" width="100%" height="350px" type="application/pdf"></iframe>
but if i use computed property then i get error in console
[Vue warn]: Error in callback for watcher "medical.name": "TypeError:
Cannot use 'in' operator to search for 'name' in null"
Should i have to initialize all variable in computed method?

Vue: Unhandled promise rejection Error: Request failed with status code 404?

My API url is http://localhost:5000/api/user/list, data shows as:
[{"Id":1,"name":"Michael","pwd":"123456","age":0,"birth":"2018-01-05","addr":"''"},{"Id":2,"name":"Jack","pwd":"123512616","age":0,"birth":"2018-01-05","addr":"''"}]
User.vue
import axios from 'axios';
export default {
data() {
return {
filters: {
name: ''
},
loading: false,
users: [
]
}
},
methods: {
getUser: function () {
axios.get('http://localhost:5000/api/user/list', function (data) {
this.$set('users', data);
})
}
},
mounted() {
this.getUser();
}
});
The error is :
Unhandled promise rejection Error: Request failed with status code 404(…)
How can I fix it?
You should register a handler for your axios request.
Currently you are using settings argument as a handler.
axios.get('http://localhost:5000/api/user/list').then(function (response) {
// this is your handler.
})
Btw, make sure you are not requesting via CORS.
In my case there was a spelling mistake in URL string. It is fixed after that correction.

VueJS Promise is failing

I have a products component and a product owner component. Each Product will have an owner
What I am trying to do
I am receiving a list of products by calling an API endpoint. When the promise is resolved, I have a list of Products. Each Product has an OwnerID. I am trying to call another API Endpoint to fetch the name of the owner and assign it to the current product being iterated.
My Code so far
<script>
var config = require('../config');
export default {
data () {
return {
products: [],
}
},
ready () {
this.getProducts().then(t => {
console.log(t);
});
},
methods : {
getProducts : function() {
let url = config.API.GetProduct
this.$http.get(url).then(response=> {
this.products = response.data.resource;
var p = this.products.map(this.getOwner);
return Promise.all(p);
}, error=> {
console.error("An error happened!")
});
},
getOwner : function(product) {
let url = config.API.GetProductOwnerName.replace('[$$$]', product.OwnerID);
var p = new Promise();
this.$http.get(url).then(response => {
product.OwnerID = response.data.resource[0].OwnerName;
p.resolve(currentObj);
});
return p;
}
}
components: {}
}
</script>
Error that I am facing
Now whenever I am trying to do that, I keep getting the following errors
Uncaught TypeError: Cannot read property 'then' of undefined
Uncaught (in promise) TypeError: Promise resolver undefined is not a function(…)
Can somebody please let me know what I am doing wrong here ?
Thanks
You don't have to recreate a new promise object. You can just return the object you want to be passed to the next call.
getProducts: function() {
let url = config.API.GetProduct
return this.$http.get(url).then(response => {
this.products = response.data.resource;
return this.products.map(this.getOwner);
}, error=> {
console.error("An error happened!")
});
},