Vue.JS import custom module - javascript

I have created a module greatings.js like this one:
function greatings() {
this.hello = function() {
return 'hello!';
}
this.goodbye = function() {
return 'goodbye!';
}
}
module.exports = greatings;
Then I imported it into main.js in VUE.JS just like:
import greatings from './assets/js/greatings';
Vue.use(greatings);
Now I would like to use it in my components but if I do it I got an error:
mounted() {
this.greatings.hello();
}
ERROR: Error in mounted hook: "TypeError: Cannot read property 'hello' of undefined"
How to fix it and be able to use my greatings?
Thanks for any help!

greatings.js file should be like this
export default {
hello() {
return "hello";
},
goodbye() {
return "goodbye!";
}
};
and import in any file you want to use like this
import greatings from './assets/js/greatings';
and call any function do you want. remove this function Vue.use(greatings);

When using Vue.use() to register a custom plugin, it has to define an install() function, which is called by Vue. From docs:
A Vue.js plugin should expose an install method. The method will be called with the Vue constructor as the first argument, along with possible options.
See the provided example, for all the options you have when creating a custom plugin: https://v2.vuejs.org/v2/guide/plugins.html

Related

How to resolve a type error in javascript/cypress

I am learning cypress and javascript and have come across this type error.
TypeError: _testElements.default.selectionRow is not a function
I looked at some documentation with cypress and can't see a mistake I am making in the code, so was hoping someone with javascript and cypress experience may know why this error is being outputted.
Code:
First the class where it gets the element:
class testElements {
selectionRow() {
return cy.get('.selectionRow')
}
typeButton() {
return cy.get('.typeButton')
}
}
export default testElements
And then the code it's referring the error to is below:
import { Given, When, Then } from "cypress-cucumber-preprocessor/steps";
import testElements from '../elements/testElements';
When ("User selects a row", () => {
testElements.selectionRow()
.within(() => {
testElements.typeButton().not(".disabled");
})
})
You should first create a class instance to use the methods:
const testElem = new testElements();
testElem.selectionRow()
And I suggest to use uppercase name convention for class TestElements.
If you don't want to instantiating the class, you can use static methods

How To import sanitize.js to react apps Function / class not found

I've some problem, in my project I need to add Sanitize.js on my project, I've copied to my own 3rd party folder ex vendor
to import it I'm using
import {san} from '../../vendor/Sanitize' //There's No error when compiling this one
but there's an error when I run the page, I'm trying to call the function from Sanitize.js as in readme saying to use it just do like this
var s = new san.Sanitize({
elements: ['a', 'span'],
attributes: {
a: ['href', 'title'],
span: ['class']
},
protocols: {
a: { href: ['http', 'https', 'mailto'] }
}
});
s.clean_node(p);
The Error is
san.Sanitize is not a function/ class constructor
Any idea why this is happening? or did I miss something? There's no Error in compiling process, the error only occurs when I try to run the web page,
Because Sanitize.js is not a module.
Maybe you can try the following solution:
Add export default Sanitize; in end of sanitize.js.
Use import Sanitize from "./sanitize"; to import it.
Remove the following code from sanitize.js.
if ( typeof define === "function" ) {
define( "sanitize", [], function () { return Sanitize; } );
}

How to add global funtions like Create, Methods, Mounted from a plugin in Vue?

For some cases, I don't want to use mixins in my Plugin.
I am trying to add a custom Methods like created(), mounted(), methods{}, so I can access its property when the component is loaded & run my custom method.
example: "customMethod"
// #root/home.vue
<script>
export default {
name: 'Home',
props: {
msg: String
},
mounted(){
//
},
methods{
//
},
customMethod{
}
}
</script>
.vue file
<script>
export default {
customMethod () { // Custom option.
console.log('custom method executed!')
},
methods: {},
created () {},
mounted () {}
}
</script>
plugins/customMethods.js
const customMethods = {
install (Vue) {
// INSTALL
if (this.installed) return
this.installed = true
Vue.options = Vue.util.mergeOptions(Vue.options, {
created: function () {
if (this.$options.customMethod) { // If found in the component.
this.$options.customMethod() // Execute the customMethod.
}
}
})
}
}
export default customMethods
main.js
import customMethods from 'plugins/customMethods.js'
Vue.use(customMethods)
What this does is extend the default options for all Vue instances so
the behavior is applied to every single Vue instance created. This is
however undocumented at the moment.
Alternatively, this can also be achieved by the use of global mixin in the plugin. (which you don't want for some reason as per your use case.)
Moreover, one advanced use case is we may need special handling when merging custom option values during Vue.extend. For example, the created hook has a special merge strategy that merges multiple hook functions into an Array so that all of them will be called. The default strategy is a simple overwrite. If you need a custom merge strategy you will need to register it under Vue.config.optionMergeStrategies:
Vue.config.optionMergeStrategies.customMethod = function (parentVal, childVal) {
// return merged value.
}
Every component can access your customMethod if you inject it into Vue.prototype like this:
Vue.prototype.customMethod = function() {}

Testing Vue components methods

I am starting with Vue.js and is really hard to find documentation about Unit Test.
I am trying to test components methods and builtin stuff as ready(). I can call those correctly but they internally have references to this object and this context is lost during testing time.
error
TypeError: this.$on is not a function
spec.js
import Vue from 'vue';
import Partners from 'components/main/partner/Partners';
describe.only('Partners.vue', () => {
it('should render with mocked partners', (cb) => {
Partners.ready(); // I get an error here because ready() is calling inside: this.$on(...)
cb(null);
});
});
component.vue
export default {
name: 'Partners',
data() {
return { };
},
methods: {
get() {
// ...
}
},
ready() {
this.$on('confirm', (confirm) => {
// ...
});
this.get();
}
};
I think ready() is depreciated along with Vue 1.0. Consider upgrading to Vue 2 (where mounted() replaces ready()).
To test your component, you need to initialize your component and a Vue instance, (and usually mount it, depending what you are doing).
Using the vue-webpack template (which uses Vue 2):
var ctor = Vue.extend(Partners)
var vm = new ctor()
vm.$mount()
now you can do things like vm.method(), and vm.mount() will automatically be called, etc.

QML elements undefined from js

I have a problems changing elements properties from js file. In my program I have main element with that structure:
import "main.js" as Main
ApplicationWindow
{
id: applicationWindow
VK {
id: vk
onReplyReady: {
if (typeof document === "string") {
var obj = JSON.parse(document)
console.log(typeof obj.response,typeof obj.count)
Main.processReply(obj.response)
} else {
Debug.log("VK UNKNOWN ERROR")
}
}
}
initialPage: Component { Auth { } }
cover: Qt.resolvedUrl("cover/CoverPage.qml")
}
In the component Auth I have that code:
Page {
id: messangesPage
Button {
id: mycoolbutton
text: "button"
onClicked: {
vk.getMessanges("lol",0)
}
}
Component.onCompleted: {
vk.getMessanges("lol",0)
}
}
So the idea of my code is pretty simple - I have vk object, that must be global. When I call vk.getMessanges, vk send request to the server and after that emit replyReady signal. In onReplyReady I just parse the reply from server and call function in main.js, where I want to execute that function:
function processReply(reply) {
mycoolbutton.text = "mycoolbutton"
}
However I got an error:
main.js:8: ReferenceError: mycoolbutton is not defined
I noticed that if I call processReply() function from component Auth, than everything works fine, but when I call from element applicationWindow than I got that error. I tried to add property alias mycoolbuttonptr : mycoolbutton in the applicationWindow, but I got another error. What I must do in that case?
Are you aware that main.js is instantiated once for every import you make? If you import main.js from several QML files, you are getting several instances of Main, so if you set a reference to mycoolbutton in one of that instances, that reference is only set on that instance.
If you want to have only one Main instance, you have to declare it at the begining of the JS file with
.pragma library
You can't access Items by id from JS file. You should pass button as parameter, for example:
function processReply(reply, btn) {
btn.text = "mycoolbutton"
}
".pragma library" can be helpful, but doesn't solve problem.

Categories