Using Vue $refs dynamically inside of function with parameter - javascript

I am trying to access a DOM element with Vue, using the $refs functionality, but I am having trouble getting it to work.
My element looks like so below. The plateId is generated dynamically, so it will not always be the same number:
<textarea :ref="plateId + '-notes'">
My Vue function looks like so:
/* This does not work */
addNotes: function(plateId) {
console.log(this.$refs.plateId + '-notes');
}
Whenever I run this code and the function is activated, it just reads undefined in my console. I've also tried this, which also does not work and reads undefined:
/* This does not work */
addNotes: function(plateId) {
var plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
Replacing var with const (I am using ES6 and transpiling the code) doesn't work either:
/* This does not work */
addNotes: function(plateId) {
const plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
I know the ref is binding correctly to the element, because when I do this below, I can see all of my other refs in the console, as well as the plateId-notes ref:
/* This works */
addNotes: function(plateId) {
console.log(this.$refs);
}
How can I access the plateId ref using the parameter in my function?

you can use the [] notation:
methods: {
foo (id) {
alert(this.$refs[id + '-test'].innerText)
}
}
A complete working example: https://jsfiddle.net/drufjsv3/2/

also, you can acces to all the $refs rendered in view by accessing
vm.$children.forEach( child => {
var tag = child.$vnode.data.ref;
console.log(vm.$refs[tag]);
vm.$refs[tag].loadData();
});
// loadData() is a method to implement when mounted or when you want to reload data
////////////////////////////////////
<script>
export default {
data() {
return {
notifications: []
}
},
mounted() {
this.loadData();
},
methods: {
loadData: function() {
axios.get('/request-json/notifications').then(res => {
this.notifications = res.data;
});
},
.....

Related

Vitest -Unable to access the DOM inside a test

I am new to front-end testing, and I am trying to get a good grasp on it.
In the process, inside one project, I am creating a test for a Vue component. I want to test that the behaviour of the code is correct (The component has code inside the mounted() hook that has to perform basically some checks and an API call).
I want to check that the code reaches one method. Previously to that, the code creates a click event listener to one element in the DOM.
My test emulates a click event (triggers it), but it cannot assert that the proper method has been called after the click event.
This is due to it not finding the element in the DOM to which it has to add the event listener. It seems that the code cannot find anything inside the document (using .getElementById()).
I wonder why, and how I would resolve this, since I have been stuck here for hours and I haven't found any solution that could work here, even when I have learned some interesting things in the process. I will leave a code example with the code structure I have built:
Inside the component:
<template>
// ...
<button id = "myButton">Add</button>
</template>
<script>
import { classInExternalScriptsFile } from "#/scripts/externalScriptsFile ";
let classIESF = new classInExternalScriptsFile();
export default {
methods: {
setup: function () {
classIESF.setupMethod();
},
},
mounted() {
this.setupMethod();
},
};
</script>
Inside the scriptsFile
export class classInExternalScriptsFile {
setupMethod() {
let myButton = document.getElementById("myButton") // <-- getElementById() returns a null here
if (typeof myButton !== "undefined" && myButton !== null) {
myButton.onclick = () => { // <-- The test code complains because it cannot enter here
// Some lines...
this.mySuperMethod()
}
}
}
mySuperMethod() {
// API call etc.
}
}
Inside the .spec.js test file:
// imports...
import { classInExternalScriptsFile } from "#/scripts/externalScriptsFile.js";
describe("description...", () => {
const mySuperMethodMock = vi
.spyOn(classInExternalScriptsFile.prototype, "mySuperMethod")
.mockImplementation(() => {});
test("That the button performs x when clicked", () => {
let wrapper = mount(myComponent, {
props: ...,
});
let myButton = wrapper.find('[test-id="my-button"]');
myButton.trigger("click");
expect(mySuperMethodMock).toHaveBeenCalled(); // <-- The test fails here
}
}

connectedCallback () on custom elements cannot use forEach to loop data on javascript

can anyone provide a solution to the problem that I'm currently encountering? I created a custom element where this custom element must have been detected on the dom, but I need to have the data contained in this custom element loaded, so my program code is like this.
import './menu-item.js';
class MenuList extends HTMLElement {
// forEach cannot be used if I use the ConnectedCallback () method
connectedCallback() {
this.render()
}
// my data can be from this method setter
set menus(menus) {
this._menus = menus;
this.render();
}
render() {
this._menus.forEach(menu => {
const menuItemElement = document.createElement('menu-item');
menuItemElement.menu = menu;
this.appendChild(menuItemElement);
});
}
}
customElements.define('menu-list', MenuList);
and this is the data I sent in the main.js file
import '../component/menu/menu-list.js';
import polo from '../data/polo/polo.js';
const menuListElement = document.querySelector('menu-list');
menuListElement.menus = polo;
please give me the solution.
The connectedCallback runs before the menus=polo statement.
So there is no this._menus declared.
If all the menus setter does is call render, then why not merge them:
set menus(menus) {
this.append(...menus.map(menu => {
const menuItemElement = document.createElement('menu-item');
menuItemElement.menu = menu;
return menuItemElement;
}));
}

How to pass js Object and functions to a web component

Hi All I am a beginner in javaScript and currently exploring JS Web-component and I got stuck due to some use cases
1 ) I want to pass a JS Object into my component like
<my-component data=obj ></my-component>
And require to use inside my component code Like
connectedCallback () {
console.log(this.data) // it should print {"name":"xyz" , "role" : "dev"}
}
2 ) I also need to pass some functions or maybe call back functions like.
function myFunction(e){
console.log(e)
}
<my-component click=myFunction ></my-component>
please try to add code snippet also in ans that will help me to learn more JS.
Thanks
You should pass large object by Javascript.
Via a custom element method:
let comp = document.querySelector( 'my-component' )
comp.myMethod( obj )
Or setting a property:
comp.data = obj
It is best to pass in complex data using a property and not an attribute.
myEl.data = {a:1,b:'two'};
The standard on events work fine on a custom element:
function myFunction(e){
alert(JSON.stringify(e.target.data));
e.target.data = {a:1,b:"two"};
}
class MyComponent extends HTMLElement {
constructor() {
super();
this._data = 0;
this.attachShadow({mode:'open'}).innerHTML="Click Me";
}
static get observedAttributes() {
return ['data'];
}
attributeChangedCallback(attrName, oldVal, newVal) {
if (oldVal !== newVal) {
}
}
get data() {
return this._data;
}
set data(newVal) {
this._data = newVal;
}
}
customElements.define('my-component', MyComponent);
<my-component onclick="myFunction(event)"></my-component>
If your component dispatches a custom event then it is best to access it through code:
function specialEventHandler(evt) {
// do something
}
myEl.addEventListener('special-event;', specialEventHandler);
I did a Udemy course with Andreas Galster and the tutor passed in a JSON object via attribute.
As you can see it needs encodeURIComponent and decodeURIComponent as well to
attributeChangedCallback (name, oldValue, newValue) {
if (newValue && name === 'profile-data') {
this.profileData = JSON.parse(decodeURIComponent(newValue));
this.removeAttribute('profile-data');
}
this.render();
}
Pass in:
<profile-card profile-data=${encodeURIComponent(JSON.stringify(profile))}>
</profile-card>
The code worked fine for me.
Ad 1) You need to use JSON.stringify(obj)
Ad 2) As far as I know All attributes need to be defined as strings. You can pass the function that is global and inside component try to eval(fn)

Calling the vue method from inside an event from VueDraggable

I am trying to get drag and drop function working in the vue.js app using vue-draggable https://vuejsexamples.com/vuejs-drag-and-drop-library-without-any-dependency/
The library has few events you can listen to and I would like to execute some logic once the item is dropped. However, I am not able to access vue component 'this' along with the data and methods. I've tried to use this.$dispatch('symDragged', event); but it is not working for the same reason. 'this' is not a vue instance but rather instance of draggable element.
Here is the code:
export default {
components: {
ICol,
SymptomsChooser, MultiSelectEditor, TempPressureChooser, BodyPartsEditor, MandatorySymptomsChooser},
data() {
return {
// data ommited...
options: {
dropzoneSelector: 'ul',
draggableSelector: 'li',
excludeOlderBrowsers: true,
showDropzoneAreas: true,
multipleDropzonesItemsDraggingEnabled: true,
onDrop(event) {
// delete symptom from old basket and add it to new one
let oldBasket = event.owner.accessKey;
let newBasket = event.droptarget.accessKey;
//this is not working
//this.symDragged(this.draggedSymId, oldBasket, newBasket);
},
onDragstart(event) {
this.draggedSymId = event.items[0].accessKey;
}
}
}
},
methods: {
symDragged(symId, oldBasketId, newBasketId) {
console.log("symDragged!");
let draggedSym = this.getSymById(symId);
let basketOld = this.getBasketById(oldBasketId);
this.delSym(basketOld, draggedSym);
this.addSym({baskedId: newBaskedId, sym: draggedSym});
}
//other methods ommited
}
}
So, what is the correct way to call the vue component method from callback event? Or maybe I need to create another event so that vue instance could listen to it?
Thanks for you help!
The problem you are facing is that with this you are referencing to the returned data object scope and not component scope. The best way to solve this is to make reference to the component instance, so later on you can call anything attached to that instance. You can also take a look at codesandbox example https://codesandbox.io/embed/7kykmmmznq
data() {
const componentInstance = this;
return {
onDrop() {
let oldBasket = event.owner.accessKey;
let newBasket = event.droptarget.accessKey;
let draggedItemsAccessKeys = event.items.map(element => element.accessKey);
componentInstance.symDragged(
draggedItemsAccessKeys,
oldBasket,
newBasket
);
}
}
}

Pass function through x-tag accessors

I am trying to use x-tag accessors but I'm not finding a good documentation about them.I would like to pass a function through an accessor and write something like this:
<my-element logic="myFunction()"></my-element>
And I want to save that function and use it later. Is there any way to do that?
I'm really not sure what you're trying to accomplish, but I'll give it a shot. If you are trying to make some logic available on all <my-element> tags, use the methods object, like this:
xtag.register('my-element', {
methods: {
logic: function (a) {
return a * 2;
}
}
});
If you want to be able to assign logic to each instance of <my-element> individually, then you could use a standard (non-attribute) accessor, and do so implicitly.
xtag.register('my-element', {
accessors: {
logic: {}
}
});
HTML
<my-element id="test"></my-element>
Set logic for one instance of <my-element>
var el = document.querySelector('my-element#test');
el.logic = function (a) {
return a * 2;
};
If you want to use an attribute to set the value of logic to a global function, you could do this:
Example global function
function myFunction(a) {
return a * 2;
}
Component
xtag.register('my-element', {
accessors: {
logic: {
attribute: {},
get: function () {
return this._logic;
},
set: function (v) {
this._logic = window[v] || null;
}
}
}
});
Usage (HTML)
<my-element logic="myFunction"></my-element>
Usage (JS)
var el = document.querySelector('my-element');
el.logic(2); // 4

Categories