Inject .js file into VueJS 3 component using provide - javascript

Im having a simple import problem in my VueJS 3 app. I have looked at this answer: Vue 3 Composition API Provide/Inject not working in Single File Components but did not find an answer.
I am importing my external file in main.js: import * as myService from "./services/myService.js";
Then also in main.js: app.provide("myService", myService);
And then in my component I have:
<script>
export default {
name: "MyComponent",
props: {
...
},
methods: {
myFunc: function(){
var result = myService.serviceFunction();
}
},
data: function(){
return {
...
}
},
inject: ["myService"]
}
</script>
But where I have var result = myService.serviceFunction(); gives me the error that myService is undefined.
If I call var result = myService.serviceFunction(); in main.js there is no error and the function is called correctly, so the problem must be with the VueJS injection.
What have I done wrong?

You should add this to get access to the injected item :
methods: {
myFunc: function(){
var result = this.myService.serviceFunction();
}
},

Related

Nuxt.js + Vue.js How to read global params in a third-party javascript with IIFE

I have one javascript IIFE, structure like this:
(Sure, Skycons, Original From Here)
import Vue from 'vue'
(function(global) {
"use strict";
// code here
global.Skycons = Skycons;
}(Vue));
Stored in '~/assests/js/Skycons.js'
And, I change the nuxt.config.js like this:
plugins: [
// other plugins
'~plugins/skycons/skycons.js',
],
'~plugins/skycons/skycons.js'is here:
import Vue from 'vue'
import '~/assets/js/skycons.js'
let myskycons = {
install(Vue) {
Vue.prototype.myskycons = {
val: function () {
return new Skycons({
color: 'pink'
});
}
};
}
}
Vue.use(myskycons);
When I use it in my compenoments, it always info the Skycons is not a function, that i cant read it

How to integrate Javascript library in Laravel9 with Vue using Laravel Mix

new to all these modern day frameworks
I'm trying to get this javascript library to work in my Vue component: https://clipboardjs.com
I can see it is integrated into my public/js/app.js file when Mix runs - but I cannot seem to be able to reference it from within my .vue (component) file
Can anyone give me a step by step guide on how to get this to integrate into my project please:
resources/js/app.js file
import './clipboard';
the clipboard.js file is located at:
resources/js/clipboard.js
Mix webpack.mix.js file:
mix.js("resources/js/app.js", "public/js")
.js("resources/js/clipboard.js", "public/js")
.vue()
.postCss("resources/css/app.css", "public/css", [
require("tailwindcss"),
]);
My Vue component (method section):
<script>
export default {
props: ['mediaDetails'],
data() {
return {
}
},
methods: {
copyPassword() {
alert("copy");
var password = document.getElementById('#password');
alert('1');
var clipboard = new ClipboardJS(password);
alert('2');
}
}
the alert('2') never fires due to the clipboard assignemnet failing
First, in your webpack.mix.js file, remove the line .js("resources/js/clipboard.js", "public/js")
Install the clipboard package: npm install clipboard
In your Vue component, import the package in order to use it:
<script>
import ClipboardJS from 'clipboard';
export default {
props: ['mediaDetails'],
data() {
return {
}
},
methods: {
copyPassword() {
alert("copy");
var password = document.getElementById('#password');
alert('1');
var clipboard = new ClipboardJS(password);
alert('2');
}
}
BTW You have a typo error in document.getElementById('#password'), it should be document.getElementById('password')

this.$route undefined in VueJS (without using arrows)

For some reason, this.$route is undefined for me. I have just started building my Vue application:
window.Vue = require('vue');
new Vue({
el : '#break-container',
data : {
break : null
},
methods : {
fetchBreak : function(){
console.log(this.$route); //undefined
},
},
mounted : function(){
this.fetchBreak();
},
});
I see a bunch of questions on SO about this, but every time the problem seems to be that they are using arrow notation.
In my case, when I do console.log(this) there is no $route key in the printed object at all. The keys ($attrs, $children, ... , $vnode, break).
What can I do to resolve this?
As I understand it, this.$route is only available on Vue instances if you register your router when you create your Vue app. Your code appears to be missing the router definition and subsequent initialisation on the Vue instance
new Vue({
el : '#break-container',
// Register your router
router: router,
data : {
break : null
},
methods : {
fetchBreak : function(){
console.log(this.$route); //undefined
},
},
mounted : function(){
this.fetchBreak();
},
});
See the sample code here for a full-fledged example. From the page above:
By injecting the router, we get access to it as this.$router as well as the current route as this.$route inside of any component
EDIT:
Pasting some example code from the link above for clarity. Note the steps 0-4 in the comments. Odds are, one of those steps are missing in your code :)
// 0. If using a module system (e.g. via vue-cli), import Vue and VueRouter
// and then call `Vue.use(VueRouter)`.
// 1. Define route components.
// These can be imported from other files
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. Define some routes
// Each route should map to a component. The "component" can
// either be an actual component constructor created via
// `Vue.extend()`, or just a component options object.
// We'll talk about nested routes later.
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. Create the router instance and pass the `routes` option
// You can pass in additional options here, but let's
// keep it simple for now.
const router = new VueRouter({
routes // short for `routes: routes`
})
// 4. Create and mount the root instance.
// Make sure to inject the router with the router option to make the
// whole app router-aware.
const app = new Vue({
router
}).$mount('#app')

Importing services in Vue.js

I have a utils service I wish to use in my Vue component:
import utils from './utils';
export default {
name: 'grid',
props: {
'gridInit': { type: Object, require: true },
'gridDataInit' : { type: Array, required: true }
},
data: function() {
return {
gridData: [],
}
},
created: function(){
this.gridData = utils.transformRawData(this.gridDataInit, this.gridInit.check);
},
}
However, I receive:
[Vue warn]: Error in created hook: "ReferenceError: utils is not defined"
How can I solve the issue? The structuring of my project with utils services is very important to me.
This code says that you have declared utils as you imported. So that was the declaration part. But what about definition? In definition there is main play happening around for which that declared utils is used in code. So I think it creates warning that it is not defined. You should use it via registering like Vue.use(componentname/pluginname). This all should be done in index.js and then should be used in components
Anyhow hope this clears for you!

Register custom filters with vue.js

I am using Vue.js with Laravel with Elixir and Browserify. I want to register some custom global filters, each in their own file. I tried to follow the docs, but I can't get it to work. This is the error I get:
Uncaught ReferenceError: Vue is not defined
Any ideas?
Here's my code:
vue/filters/reverse.js
Vue.filter('reverse', function (value) {
return value.split('').reverse().join('')
})
vue/app.js
var Vue = require('vue');
Vue.use(require('vue-resource'));
new Vue({
el: 'app',
data: {
test: 'abcde'
},
filters: {
reverse: require './filters/reverse.js'
}
});
View
<h1 v-text="test | reverse"></h1>
If I add this in reverse.js, it still doesn't work
var Vue = require('vue');
And my gulpfile
mix.browserify('app.js');
Try like this in vue/filters/reverse.js
module.exports =(function (value) {
return value.split('').reverse().join('')
})
And then in your app.js
Vue.filter('reverse', require('./filters/reverse'))

Categories