Search Results
737 results found with an empty search
- Node.js Global Objects
What are Node.js Global Objects ? Node.js global objects are global in nature and they are available in all modules. We do not need to include these objects in our application, rather we can use them directly. These objects are modules, functions, strings and object itself are explained as: 1) __filename The __filename represents the filename of the code being executed. This is the resolved absolute path of this code file. For a main program, this is not necessarily the same filename used in the command line. The value inside a module is the path to that module file. Example: Create a js file and name it home.js with the following code: // Let's try to print the value of __filename console.log( __filename ); Now run the home.js to see the result: $ node home.js Based on the location of your program, it will print the main file name as follows: /project/example/node/home.js 2) __dirname The __dirname represents the name of the directory that the currently executing script resides in. Example: Create a js file name it home.js with the following code: // Let's try to print the value of __dirname console.log( __dirname ); Now run the home.js to see the result: $ node home.js Based on the location of your program, it will print current directory name as follows: /project/example/node 3) setTimeout(cb, ms) The setTimeout(cb, ms) global function is used to run callback cb after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer. Example: Create a js file and name it home.js with the following code: function printHello() { console.log( "Hello, World!!!"); } // Now call above function after 3 seconds setTimeout(printHello, 3000); Now run the home.js to see the result: $ node home.js Verify the output is printed after a little delay. Hello, World!!! 4) clearTimeout(t) The clearTimeout(t) global function is used to stop a timer that was previously created with setTimeout(). Here t is the timer returned by the setTimeout() function. Example: Create a js file and name it as home.js with the following code: function printHello() { console.log( "Hello, World!!!"); } // Now call above function after 3 seconds var t = setTimeout(printHello, 3000); // Now clear the timer clearTimeout(t); Now run the home.js to see the result: $ node home.js Verify the output where you will not find anything printed. 5) setInterval(cb, ms) The setInterval(cb, ms) global function is used to run callback cb repeatedly after at least ms milliseconds. The actual delay depends on external factors like OS timer granularity and system load. A timer cannot span more than 24.8 days. This function returns an opaque value that represents the timer which can be used to clear the timer using the function clearInterval(t). Example: Create a js file and name it as home.js with the following code: function printHello() { console.log( "Hello, World!!!"); } // Now call above function after 3 seconds setInterval(printHello, 3000); Now run the home.js to see the result: $ node home.js The above program will execute printHello() after every 3 second. Due to system limitation. Global Objects There are few other objects which we frequently use in our applications. They are: 1. Console Used to print information on stdout and stderr. 2. Process Used to get information on current process. Provides multiple events related to process activities. Node.js Console Node.js console is a global object and is used to print different levels of messages to stdout and stderr. There are built-in methods to be used for printing informational, warning, and error messages. It is used in synchronous way when the destination is a file or a terminal and in asynchronous way when the destination is a pipe. Console Methods Following are the list of methods available with the console global object. 1) console.log([data][, ...]): Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. 2) console.info([data][, ...]): Prints to stdout with newline. This function can take multiple arguments in a printf()-like way. 3) console.error([data][, ...]): Prints to stderr with newline. This function can take multiple arguments in a printf()-like way. 4) console.warn([data][, ...]): Prints to stderr with newline. This function can take multiple arguments in a printf()-like way 5) console.dir(obj[, options]): Uses util.inspect on obj and prints resulting string to stdout. 6) console.time(label): Mark a time. 7) console.timeEnd(label): Finish timer, record output. 8) console.trace(message[, ...]): Print to stderr 'Trace :', followed by the formatted message and stack trace to the current position. Node.js Process The process object is a global object and can be accessed from anywhere. There are several methods available in a process object. Process Events The process object is an instance of EventEmitter and emits the following events: 1) exit: Emitted when the process is about to exit. There is no way to prevent the exiting of the event loop at this point, and once all exit listeners have finished running, the process will exit. 2)beforeExit: This event is emitted when node empties its event loop and has nothing else to schedule. Normally, the node exits when there is no work scheduled, but a listener for 'beforeExit' can make asynchronous calls, and cause the node to continue. 3) uncaughtException: Emitted when an exception bubbles all the way back to the event loop. If a listener is added for this exception, the default action (which is to print a stack trace and exit) will not occur. 4) Signal Events: Emitted when the processes receives a signal such as SIGINT, SIGHUP, etc. If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com Node.js, Node.js Global Objects, Node.js Console, Node.js Assignment, Node.js Assignment Help, Node.js Project, Node.js Process
- Vue.js Render Function
What is Vue.js Render Function ? We have seen components and the usage of it. For example, if we have a content that needs to be reused across the project. We can convert the same as a component and use it. We will consider an example of a simple component and see what the render function has to do within it. render.html From the above example of a simple component that prints Hello World!!! as shown in the image. Output: Now, if we want to reuse the component, we can do so by just printing it again and again. For example, . And the output will be as. Now, if we need some changes to the component. We don’t want the same text to be printed. How can we change it? In this case, we have to type something inside the component, will it be taken into consideration? Let us understand with the help of following example and see what happens. Hello Raj! Hello Jai! Hello Mia! Hello Vij! . Hello Ian! The output remains the same as we had seen earlier. It does not change the text as we have wanted. So we have to use slots. Component does provide something called as slots. Now, we will use it see if we get the desired results. What Are Slots? Slots are a mechanism for Vue components that allows you to compose your components in a way other than the strict parent-child relationship. Slots give you an outlet to place content in new places or make components more generic. The best way to understand them is to see them in action. Let’s start with a simple example: // frame.vue . . . Slot Content Slots are a powerful tool for creating reusable components in Vue.js. Vue implements a content distribution API inspired by the Web Components spec draft, using the element to serve as distribution outlets for content. renderslot.html As seen in the above code, in the template we have added slot, hence now it takes the value to send inside the component as shown in the output. Output: If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com Vue.js, Vue.js Rendering, Vue.js Render, Vue.js Rendering Assignment, Vue.js Assignment Help, Vue.js Project, Vue.js Slots
- Python Programming Help | Python Homework Help | Codersarts
Step 1. Construct a text file that follows the input specifications of the problem, i.e. it can serve as a sample input. Specifically, you should give an input file representing a 10x10 patch. The patch should contain two or three islands, according to your choice. The shape of the islands can be arbitrary, but try to be creative. The text file should be of the form firstname-lastname.txt. Notice that each cell in the patch is characterized by its coordinates. The top left coordinate is (0,0) and coordinate (i,j) is for the cell in the i-th row and j-th column. Step 2. Write a function that reads an input file with the given specifications and returns the list of the coordinates of the land points, i.e. the list of coordinates for the ‘X’ points. Suppose now that the input is an m×n patch. This means that there are mn different coordinates. Step 3. Write a function CoordinateToNumber(i,j,m,n) that takes a coordinate (i,j) and maps it to a unique number t in [0,mn−1], which is then returned by the function. Step 4. Write a function NumberToCoordinate(t,m,n) that takes a number t and returns the corresponding coordinate. This function must be the inverse of CoordinateToNumber. That is, for all i,j,m,n we must have NumberToCoordinate(CoordinateToNumber(i,j,m,n),m,n) = (i,j) The two steps above mean that besides its coordinates, each cell has its own unique identity number in [0,mn−1] Step 5. Write a function Distance(t1,t2), where t1 and t2 are the identity numbers of two cells, and the output is the distance between them. The distance is the minimum number of connected cells that one has to traverse to go from t1 to t2. (Hint: Use function NumberToCoordinate for this) Recall that in Step 2 of Milestone 1 we wrote a function for finding the list of land cells. Let’s call this function FindLandCells, and its output LandCell List. This list of land cells can look like this: LandCell List = [10, 11, 25, 12, 50, 51, 80, 81, 82] (this is only an example, it does not correspond to some specific input). Now this lists can be further broken into islands. So, we have something that looks like this: Island List = [[10, 11, 12], [25], [50, 51], [80, 81, 82]] You see how all the cells from the original list appear in the second data structure, which is a list of lists, with each list being an island. Observe how cells belonging to the same island (e.g. cell 12), can be mixed up with other islands in LandCell List. In other words, one island’s cells do not have to be in contiguous positions in LandCell_List. In this milestone, we will write functions to help find the list of islands. Step 6. Write a function GenerateNeighbors(t1, n, m), that takes one cell number t1 (and also the dimensions), and returns the numbers for the neighbors of t1 in the grid. Notice that t1 can have 2, 3, or 4 neighbors. Step 7. Write a function ExploreIsland(t1, n, m). This function should start from cell t1, and construct a list of cells that are on the same island as t1. (Hint: t1 can add itself to a dictionary representing the island, and also its neighbors, then the neighbors should recursively do the same. But when new neighbors are inserted in the dictionary, we should first check if they are already in it. The process should terminate when it’s not possible to add more cells to the dictionary, meaning that we found the island. Finally, the function should return a list with the cells on the island) Step 8. Write a function FindIslands that reads the list LandCell List and converts its to Island List as explained above. The idea for this step is to scan the list of land cells and call repeatedly the ExploreIsland function Step 9. Write a function Island Distance(isl1, isl2), which takes two lists of cells representing two islands, and finds the distance of these two islands. For this, you will need to compute the Distance function Step 10. We will now construct a graph of islands. Consider an example of this. Suppose Island List contains 3 islands. We will assign to each island a unique number in [0, 3). Then Island Graph will be a list of the following form: [[0, 1, d(0, 1)], [0, 2, d(0, 2)], [1, 2, d(1, 2)]]. Here d(i, j) is the distance between islands i and j, as computed with the function in Step 9. In other words, for each pair of islands, we have a triple consisting of the identities of the pair, and their distance. This is a complete weighted graph. The goal of this Step is to write a function Island Graph that outputs this list. Final Step. We now have a data structure which is the adjacency list (with weights) of the graphs. To connect all islands, we need to find a minimum-weight spanning tree for this graph. However, for this assignment, I will ask you to use the python library networkx. Here is the documentation of a function that computes minimum-weight spanning trees. https://networkx.github.io/documentation/networkx 1.10/reference/generated/networkx. algorithms.mst.minimum_spanning_tree.html#networkx.algorithms.mst.minimum_spanning_ tree The task in this final step will be to familiarize yourself with this documentation. Island Graph is a list that has all information needed, and it just needs a bit more work to convert it in the appropriate format that can be handled by networkx. So, your task will be to do this conversion, then run the MST function and find the tree. Finally, you should compute the total length (weight) of the edges in the tree, so that the question of the problem is answered. Codersarts is a top-rated website for students which is looking for online Programming Assignment Help, Homework Help, Coursework Help in C, C++, Java, Python, Database, Data structure, Algorithms, Final year project, Android, Web, C sharp, ASP NET to students at all levels whether it is school, college and university level Coursework Help or Real-time project. Hire us and Get your projects done by computer science expert If you have project or assignment files, You can send at contact@codersarts.com directly
- Design a Cryptocurrency | Python Network Programming Assignment Help | Codersarts
What is the Main Idea? In this project, we will design a cryptocurrency similar to ScroogeCoin. A network of 100 users will simulate the transaction processes. Initially, each user will have 10 ScroogCoins. As long as the system is running, a random transaction with a random amount (within the range of amount the user has) will be created from User A to User B. The transaction is signed by the private key of the sender. Scrooge gets notified by every transaction. Scrooge verifies the signature before accumulating the transaction. Once Scrooge accumulates 10 transactions, he can form a block and attach it to the blockchain. You are allowed to use predefined hash and digital signature libraries. Mention which libraries you used. General Deliverables A designated entity “Scrooge” publishes an append-only ledger that contains all the history of transactions. ❖ The ledger is a blockchain, where each block contains transactions, its ID, the hash of the block, and a hash pointer to the previous block. The final hash pointer is signed by Scrooge. ❖ A simulation of the network, with multiple users and the randomized process of making a transaction, making each transaction reach an arbitrary user. ❖ The design and implementation of the ledger based on the concept of the blockchain (hash linked list). ❖ Upon detecting any transaction, scrooge verifies it by making sure the coin really belongs to the owner and it has not been spent before. ❖ If verified, Scrooge adds the transaction to the blockchain. Double spending can only happen before the transaction is published. ❖ For the digital signature, use any of the techniques described throughout the course. Output Format ❖ Print initially the public key and the amount of coins for each user. ❖ Scoorge should print the block under construction for each new transaction added (include the transaction details). ❖ Print the blockchain after a new block is appended. ❖ Terminate the code using the key ‘Space’. ❖ Save all the printed data to a text file upon termination. Contact us for this machine learning assignment Solutions by Codersarts Specialist who can help you mentor and guide for such machine learning assignments. If you have project or assignment files, You can send at contact@codersarts.com directly
- Machine Learning Top 20 Projects | Machine Learning Homework Help | Codersarts
Project 1: Pandas (for basic understanding) Project 2: Exploratory Data Analysis on Haberman Dataset Project 3: Implementing TFIDF vectorizer Project 4: Implement RandomSearchCV with k fold cross-validation on KNN Project 5: Compute Performance metrics without Sklearn Project 6: Apply Naive Bayes on Donors Choose dataset Project 7: Implement SGD Classifier with Logloss and L2 regularization Using SGD without using sklearn Project 8: Behavior of Linear Mode+ls Project 9: Apply Decision Trees on Donors Choose the dataset Project 10: Application of Bootstrap samples in Random Forest Project 11: Apply GBDT on Donors Choose dataset Project 12: Clustering on Graph Dataset Project 13: Recommendation Systems and Truncated SVD SGD algorithm to predict ratings Project 14: Microsoft Malware Detection Project 15: Facebook Friend Recommendation Project 16: SQL Assignment on IMDB data Project 17: Working with Callbacks Project 18: Transfer Learning Project 19: Document Classification with CNN Project 20: LSTM on Donors Choose Project 21: CNN on CIFR If you are beginners in machine learning and need a solution to the above topics then you can contact us and get instant help with us. Contact us for this machine learning assignment Solutions by Codersarts Specialist who can help you mentor and guide for such machine learning assignments. If you have project or assignment files, You can send at contact@codersarts.com directly
- Vue.js Routing
What is Vue.js Routing ? Vue.js does not have a built-in router feature. We need to follow some additional steps to install it. Direct Download from CDN The latest version of vue-router is available at https://unpkg.com/vue-router/dist/vue-router.js Unpkg.com provides npm-based cdn links. The above link is always updated to the recent version. We can download and host it, and use it with a script tag along with vue.js as follows: Using NPM To install router using NPM we have to run the following command: npm install vue-router Using GitHub We can also install router from GitHub, for this we have to clone the repository from GitHub as follows: git clone https://github.com/vuejs/vue-router.git node_modules/vue-router cd node_modules/vue-router npm install npm run build We will start with a simple example with vue-router.js. router.html Output: When we click on Router Link 1 the browser will display it like this and when we click on Router link 2 the page will be like the one on the right side. To start with routing, we need to add the vue-router.js file. Copy the code from https://unpkg.com/vue-router/dist/vue-router.js and save it in the file vue-router.js. The script to add the file is added after vue.js as follows: In the body section, there is a router link defined as follows: . . Router Link 1 . Router Link 2 is a component used to navigate to the HTML content to be displayed to the user. The to property is the destination, i.e the source file where the contents to be displayed will be picked. In the above code, we have created two router links. Look at the script section where the router is initialized. There are two constants created as follows: const Route1 = { template: 'This is router 1' }; const Route2 = { template: 'This is router 2' } They have templates, which needs to be shown when the router link is clicked. Next, is the routes const, which defines the path to be displayed in the URL. const routes = [ . { path: '/route1', component: Route1}, . { path: '/route2', component: Route2} ]; Routes define the path and the component. The path i.e. /route1 will be displayed in the URL when the user clicks on the router link. Component takes the templates names to be displayed. The path from the routes need to match with the router link to the property. For example, Next, the instance is created to VueRouter using the following piece of code. const router = new VueRouter({ . routes // short for `routes: routes` }); Props for Router Link Let us see some more properties to be passed to . 1) to This is the destination path given to the . When clicked, the value of to will be passed to router.push() internally. The value needs to be a string or a location object. When using an object, we need to bind it. e.g. 1: RouterLink1 . renders as Router Link e.g.2: . RouterLink1 e.g.3: RouterLink1 . //router link with query string. 2) replace Adding replace to the router link will call the router.replace() instead of router.push(). With replace, the navigation history is not stored. Example Router Link 1 3) append Adding append to the will make the path relative. If we want to go from the router link with path /route1 to router link path /route2, it will show the path in the browser as /route1/route2. Example Router Link 1 4) tag At present renders as a tag. In case, we want to render it as some other tag, we need to specifty the same using tag = ”tagname”; Example Router Link 1 Router Link 2 We have specified the tag as span and this is what is displayed in the browser. The tag displayed now is a span tag. We will still see the click going as we click on the router link for navigation. 5) active-class By default, the active class added when the router link is active is router-link-active. We can overwrite the class by setting the same as shown in the following code. Router Link 1 Router Link 2 The class used is active_class = ”_active”. This is the output displayed in the browser. 6) exact-active-class The default exactactive class applied is router-link-exact-active. We can overwrite it using exact-active-class. Example Router Link 1 Router Link 2 7) event At present, the default event for router-link is click event. We can change the same using the event property. Example Router Link 1 If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com Vue.js, Vue.js Routing, Vue.js Routing Install, Vue.js Routing Assignment, Vue.js Assignment Help, Vue.js Project
- Hostel Accommodation System Using Java | Codersarts
Overview Affirvat Hostels provides affordable accommodation to students pursuing coaching for various competitive examinations in metropolitan cities. It requires a software application that can be used by its staff to manage various operations. Some of the main operations are as follows: Book a room Vacate a room Display available rooms Search room details Display summary information about rooms You are required to develop an application using Java that will allow the hostel staff to interactively perform various tasks as stated above. Assignment Requirements: You are required to write the following three classes: Room: A class, defines a simple object type representing a room. Hostel: A class, defines objects which are containers of Room objects. HostelMain: A driver class that creates one Hostel object and allows the various methods of Hostel to be called. This class will provide an interactive application interface using the keyboard and the screen to the hostel staff. This is only providing an interface and will not do calculations itself but will immediately pass user inputs as arguments to methods of Hostel class. NOTE: The final application will only execute correctly when all three classes have been defined completely and correctly but don't wait until you have completely written all three before you start compiling and testing your code. It is recommended that you save all three source code files in the same directory on your file system and compile and test each class as you develop it using small separate programs to create and test objects of each class. The files The files you will require are: Room.java This file defines a class of Room objects. The objects have the following instance variables: number of beds in the room, of type integer; guest’s name, of type String; booking status of a room – if the room has been booked, the status is 'true', otherwise it is 'false'; room tariff, i.e. cost of using the room for one night, of type double; The methods of class Room should include: A default constructor. This constructor should initialize a Room object with the number of beds as two, the guest's name as "Nobody", the booking status as false, and the room cost to 100.00. This is the default state of a Room object. A Setter method that accepts one argument which is used to set the number of beds. It must ensure that the number of beds stored in the Room object remains in the range 1-4 inclusive. A Setter method for the room tariff. This method accepts one argument representing a new tariff value. It must ensure the tariff is not negative. A method called bookRoom which accepts a String argument representing a guest’s name. It sets the booking state to true and assigns the parameter value to the guest's name variable. A method called vacateRoom which sets the booking state to false and sets the guest's name variable back to "Nobody". A getter method for each of the class members which are the number of beds, the tariff, and the guest's name - these return the appropriate value. A boolean method called isBooked which returns the booking status. A 'toString' method which returns a single String containing the details of a room with format as described below: Room with beds, tariff , and guest named . or Room with beds, tariff , and is vacant. Example: Room with 2 beds, tariff 100.00, and a guest named James Bond. or Room with 2 beds, tariff 100.00, and is vacant. It is recommended that once you have written the Room class, you create a program to test it. The testing program should be placed in the same working directory as the Room class and be used to create one or two Room objects and call some of the Room methods. Compile the Room class and compile and run the test program to check your work. Hostel.java This file declares a class that maintains a collection of Room objects. It will contain methods that enable the collection to show the appropriate behavior as required by the menu. This file should be saved into the same working directory as Room.java. The Hostel class should declare an array of Room objects; no additional attribute is allowed. The Hostel class must also contain methods that allow the collection of rooms to be managed. These methods should include: A constructor that accepts an integer is used to set the size of the Room array. If the integer value passed in is invalid, then an array of Room objects of size 50 is to be created. If the parametric integer is valid, that is between 20 and 100, inclusive, then a Room array of the specific parametric value will be created. Next, you need to perform some initialization tasks for the rooms as described below. Each task can be defined as a private method, and the constructor will then invoke these methods to complete the task: The first task is to traverse the array and instantiate a default Room object referenced by each array cell. After each Room has been instantiated, we will assume that the array index will represent the room number in the hostel. For example, room number 2 will be in the array cell with index 2, room numbered 5 will be in the array cell with index 5, etc. The second task is to traverse the array and set the room tariff of all the even-numbered rooms to $150.00, except room numbered 0, which is set to $1500.00 as it is the penthouse suite. The third task is to set the number of beds to 1 for the last 5 rooms and set the number of beds to 4 for rooms 1 through 5 inclusive. A method named getRoom which accepts an integer parameter representing a room number and returns a reference to the Room object in that cell of the array. If the parametric integer is illegal, a null reference should be returned. A method named numOfBookedRooms which does not accept any parameter, and returns the number of rooms which are booked. A method named numOfVacantRooms which does not accept any parameter, and returns the number of rooms which are not booked. A method named totalTariff which does not accept any parameter, and returns the total value of all the tariffs of all the booked rooms. This simulates one day's income for the hostel. A method named getAvailableRooms which accepts an integer representing a number of guests which need a room. This method should return a String in which there is a list of all the vacant rooms which have enough beds for the prospective guests. A method named findGuestRoomNumber which accepts a String representing a guest's name and searches through all the rooms looking for the first guest whose name is the same as the parametric name. The method should return the number of the room when a match is found. If the name cannot be found, the method should return -1. When you have written the Hostel class - test it by creating a Hostel object and invoking the methods from a Java program HostelMain.java The aim of this class is to provide a user-interface for a modest application which uses a Hostel container class and should be saved in the same working directory as the previous files. It is recommended that this user-interface be written as a 'console' application using the normal screen and keyboard to interact with a user via a simple text-based menu. The user-interface should create a single Hostel object and provide a menu of choices to the user with the following choices: 1 See available rooms for 'n' guests The operator enters the number of guests needing accommodation. This value should then be passed to the getavailablerooms method of the Hostel object, the returned String captured and displayed. This tells the operator which rooms can be booked. 2 Book a room The operator enters the name of the guest, then fetches the Room object of an appropriate empty room (using the 'getRoom' method) and books it with the guest's name. 3 Vacate a room The operator enters the room number of the room to be vacated, the Room object with that number is obtained using 'getRoom' and vacated. If the room is not booked, display an appropriate message. 4 Find which room a guest is in. The operator enters a guest's name and this is passed to the 'findGuestRoomNumber' method and the room number is displayed. If no such guest is found, display an appropriate message. 5 Print a report Display the number of booked rooms the number of empty rooms the total tariff of all booked rooms 6 Quit the program. Each time the user selects one of the previous options, and the program does that task, the menu should be presented again. If they choose to quit, the program should end. Feel free to contact us and take the advantages of Java assignment help services offered by us. We are the best assignment writing service provider and to solve all your academic worries. You can easily connect with us through phone, e-mail, or live chat. You can contact us anytime; our experts are always available for your help. Besides this, We will also provide CONSULTANCY for your app for FREE! so, if you are still reading this and have an app idea, drop us a message, we can surely talk and discuss your project and get things done!. You are just one step away to get it done.
- Vue.js Directive and Mixin
What is Vue.js Directives ? Directives are instruction for Vue.js to do things in a certain way. We have already seen directives such as v-if, v-show, v-else, v-for, v-bind , v-model, v-on, etc. Here, we will learn about custom directives. We will create a global directives similarly we have created for components. Syntax: Vue.directive('nameofthedirective', { . bind(e1, binding, vnode) { . } }) Hook Functions A directive definition object can provide several hook functions (all optional): bind: called only once, when the directive is first bound to the element. This is where you can do one-time setup work. inserted: called when the bound element has been inserted into its parent node. update: called after the containing component’s VNode has updated, but possibly before its children have updated. The directive’s value may or may not have changed, but you can skip unnecessary updates by comparing the binding’s current and old values. Now we will learn about the arguments passed into these hooks (i.e. el, binding). Directive Hook Arguments Directive hooks are passed these arguments: el: The element the directive is bound to. This can be used to directly manipulate the DOM. binding: An object containing the following properties. name: The name of the directive, without the v- prefix. value: The value passed to the directive. For example in v-my-directive="1 + 1", the value would be 2. expression: The expression of the binding as a string. For example in v-my-directive="1 + 1", the expression would be "1 + 1". arg: The argument passed to the directive, if any. For example in v-my-directive:foo, the arg would be "foo". modifiers: An object containing modifiers, if any. For example in v-my-directive.foo.bar, the modifiers object would be { foo: true, bar: true }. We need to create a directive using Vue.directive. It takes the name of the directive as shown above. We will learn it with the help of an example to show the details of the working of directives. directive.html In the above example, we have created a custom directive changestyle as shown in the code below. Vue.directive("changestyle",{ . bind(e1,binding, vnode){ . console.log(e1); . e1.style.color = "orange"; . e1.style.fontSize = "40px"; . } }); We are assigning the following changestyle to a div. VueJS Directive When we open a browser, it will display the text This is a Vue.js Directive in orange color and the fontsize is increased to 40px. Output: We have used the bind method, which is a part of the directive. It takes three arguments e1, the element to which the custom directive needs to be applied. Binding is like arguments passed to the custom directive, e.g. v-changestyle = ”{color:’orange’}”, where orangewill be read in the binding argument and vnode is the element, i.e. nodename. What is Vue.js Mixin ? Mixins are basically used with components. They share reusable code among components. When a component uses mixin, all options of mixin become a part of the component options. mixin.html Output: When a mixin and a component contain overlapping options, they are merged. If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com Vue.js, Vue.js Directives, Vue.js Assignment Help, Vue.js Project
- Vue.js Transition and Animation
There are various transition and animation features available in Vue.js. Transition Vue.js provides various ways to apply transition to the HTML elements when they are added in the DOM. Vue.js has a built-in transition component that needs to be wrapped around the element, which needs transition. Syntax . We will consider an example to understand the working of transition. transition.html There is button called Click Here created using which we can change the value of the variable show to true to false and vice versa. There is a p tag which shows the text element only if the variable is true. We have wrapped the p tag with the transition element as shown in the following piece of code. . Animation Example The name of the transition is fade. VueJS provides some standard classes for transition and the classes are prefixed with the name of the transition. Following are some standard classes for transition: v-enter: This class is called initially before the element is updated/added. Its the starting state. v-enter-active: This class is used to define the delay, duration, and easing curve for entering in the transition phase. This is the active state for entire and the class is available during the entire entering phase. v-leave: Added when the leaving transition is triggered, removed. v-leave-active: Applied during the leaving phase. It is removed when the transition is done. This class is used to apply the delay, duration, and easing curve during the leaving phase. Each of the above classes will be prefixed with the name of the transition. We have given the name of the transition as fade, hence the name of the classes becomes .fade_enter, .fade_enter_active, .fade_leave, .fade_leave_active. The .fade_enter_active and .fade_leave_active are defined together and it applies a transition at the start and at the leaving stage. The opacity property is changed to 0 in 2 seconds. The duration is defined in the .fade_enter_active and .fade_leave_active. The final stage is defined in the .fade_enter, .fade_leave_to. The display in the browser is as follows. Output: On the click of the button, the text will fade away in two seconds. After two seconds, the text will disappear completely. Animation Animations are applied the same way as transition is done. Animation also has classes that needs to be declared for the effect to take place. We will consider an example to see how animation works. animation.html To apply animation, there are classes same as transition. In the above code, we have an image enclosed in p tag as shown in the following code. . . . The name of the transition is shiftx. The class applied is as follows: The class is prefixed with the transition name, i.e. shiftx-enter-active and .shiftx-leave-active. The animation is defined with the keyframes from 0% to 100%. There is a transform defined at each of the keyframes. We can see the output in any browser. Output: On clicking the button, it rotates from 0 to 360 degree and disappears in 2 sec time. If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com
- Vue.js Events and Rendering
Vue.js Events We can use the v-on directive to listen to DOM events and run some JavaScript when they’re triggered. There are various HTML events. Here are a lists of some common events: Click Event We are going to explore it with the help of an example clickevent.html The following code is used to assign a click event for the DOM element. Click Here Output: On clicking the button, it will call the method ‘displaynumbers’, which takes in the event and display the result in the browser as shown in the below image. Event - Key Modifiers Vue.js offers key modifiers based on which we can control the event handling. Consider we have a textbox and we want the method to be called only when we press Enter. We can do so by adding key modifiers to the events as follows Syntax: The key that we want to apply to our event is V-on.eventname.keyname as shown above. We can make use of multiple keynames. For example, V-on.keyup.ctrl.enter keymodifier.html Output: When we type something in the textbox, we will see it is displayed once we press Enter. Vue.js Conditional Rendering We will work on a example first to explain the details for conditional rendering. With conditional rendering, we want to output only when the condition is met and the conditional check is done with the help of if, if-else, if-else-if, show, etc. v-if ifrendering.html Output: In the above example, we have created a button and two h1 tags with the message. A variable called show is declared and initialized to a value true. It is displayed close to the button. On the click of the button, we are calling a method showdata, which toggles the value of the variable show. This means on the click of the button, the value of the variable show will change from true to false and false to true. We have assigned if to the h1 tag as shown in the following code snippet. Click Me This is h1 tag Now what it will do is, it will check the value of the variable show and if its true the h1 tag will be displayed. Click the button and view in the browser, as the value of the show variable changes to false, the h1 tag is not displayed in the browser. It is displayed only when the show variable is true. Following is the display in the browser. If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com
- Vue.js Watchers and Binding
Vue.js Watchers While computed properties are more appropriate in most cases, there are times when a custom watcher is necessary. That’s why Vue provides a more generic way to react to data changes through thewatchoption. This is most useful when you want to perform asynchronous or expensive operations in response to changing data. With the help of an example, we will try to learn and use the Watch property. watchers.html In the above code, we have created two textboxes, one with hours and another with minutes. In data property, the hours and minutes are initialized to 0. There is a watch object created with two functions hours and minutes. In both the functions, the conversion from hours to minutes and from minutes to hours is done. As we enter values inside any of the texboxes, whichever is changed, Watch takes care of updating both the textboxes. We do not have to specially assign any events and wait for it to change and do the extra work of validating. Watch takes care of updating the textboxes with the calculation done in the respective functions. We can see the results in the browser. Output: Vue.js Binding Now, we will learn how to manipulate or assign values to HTML attributes, change the style, and assign classes with the help of binding directive called v-bind in Vue.js. We will try to understand why we need and when to use v-bind directive for data binding with the help of an example. databinding.html: Here, we have displayed a title variable and three anchor links. We have also assigned a value to the href from the data object. Now, if we check the output in the browser and inspect, we will see the first two anchor links do not have the href correctly as shown below. Output: The first clickme shows the href as hreflink, and the second one shows it in {{hreflink}}, while the last one displays the correct url that we require. Hence, to assign values to HTML attributes, we need to bind it with the directive v-bind as follows. Click Me Binding HTML Classes To bind HTML class, we need to use v-bind: class. We will learn the need and use of class binding with the help of an example. bindclass.html: There is a div created with v-bind: class=” {active: isactive}”. Here, isactive is a variable which is based on true or false. It will apply the class active to the div. In the data object, we have assigned the isactive variable as true. There is a class defined in the style .active with the background color as cyan. If the variable isactive is true, the color will be applied otherwise not. Here is the output of the above code in a browser. Output: In the above image, we can see the background color is changed. So, we can say that the class = ”active” is applied to the div. If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com
- Vue.js Components and Computed Properties
What is Vue Components ? Vue Components are one of the important features of Vue.js that creates custom elements, which can be reused in HTML. Let us consider an example and create a component, that will help us understand how components work with Vue.js. component.html In the component.html file, we have created two div with id test1_component and test2_component. compnent.js In the component.js file, we have created two Vue instances with the div ids. We have created a common component to be used with both the view instances. To create a component, following is the syntax. Vue.component('nameofthecomponent',{ . // options }); Once a component is created, the name of the component becomes the custom element and the same can be used in the Vue instance element created, i.e. inside the div with ids test1_component and test2_component. In the component.js file, we have used a test component as the name of the component and the same name is used as the custom element inside the component.html divs. . . The component created in the component.js file, we have added a template to which we have assigned a HTML code. This is a way of registering a global component, which can be made a part of any vue instance. The browser will display the same instances. Output: Dynamic Components Dynamic components are created using the keywordand it is bound using a property as shown in the following example: dynamic_component.html Output: The dynamic component is created using the following syntax. It has v-bind:is = ”view”, and a value view is assigned to it. View is defined in the Vue instance as follows. var vm = new Vue({ . el: '#databinding', . data: { . view: 'component'}, . components:{ . 'component':{ . template:'Dynamic . Component' . } . } }); What is Vue.js Computed Properties ? Vue Computed properties are like methods but with some difference in comparison to methods. After learning the difference, we will be able to make a decision on when to use methods and when to use computed properties. Let us consider an example to understand computed properties: computed_property.html computed_property.js Here, we have created computed_property.html file with firstname and lastname. Firstname and Lastname is a textbox which are bound using properties firstname and lastname. We are calling the computed method getfullname, which returns the firstname and the lastname entered. computed :{ . getfullname : function(){ . returnthis.firstname +" "+this.lastname; . } } When we type anything in the textbox the same is returned by the function, when the properties firstname or lastname is changed. Thus, with the help of computed we don’t have to do anything specific, such as remembering to call a function. With computed it gets called by itself, as the properties used inside changes. The same will be displayed in the browser. Type the values in the textbox and the same will get updated using the computed function. Output: If you have any queries regarding this blog or need any help you can contact us on: contact@codersarts.com











