fabiochiu/medium-articles huggingface dataset:
BreadCrumbs with Vue Router Params + Vuetify
By: Vinicius Silveira Alves
Tags: JavaScript, Vuejs, Vue Router, Vue, Vuetify

The Strategy

The component from Vuetify we are going to use is this.

Reading the documentation you’ll notice that this component receives an object like that:

items: [

{

text: 'Dashboard',

disabled: false,

href: 'breadcrumbs_dashboard',

},

{

text: 'Link 1',

disabled: false,

href: 'breadcrumbs_link_1',

},

{

text: 'Link 2',

disabled: true,

href: 'breadcrumbs_link_2',

},

],

}),

}

So, let’s give this object to the component using the famous Vue Router. This is the main strategy.

Let’s do it now!

Photo by Goran Ivos on Unsplash

I guess you alredy know how to create a Vue Project and how to add Vuetify to it.

We’ll have a few view components: Home.vue, PageB.vue, PageC.vue. And the main component : BreadCrumb.vue.

First of all, let’s configure the router, which plays an important role in this project as you read before.

Index.ts (Router)

We are using the ‘meta’ param from Vue Router and inside that creating an attribute called ‘breadCrumb’ which returns an array of objects.

But when we need to receive params from the router, we can define a function to return it.

This array will be injected into the v-breadcrumb component.
The Vue.js Created Lifecycle Hook Explained With Example
By: John Philip
Tags: Vuejs Development, Vuejs 3, JavaScript, Vuejs, Web Development

What is a lifecycle hook?

Lifecycle hooks are pure functions whose context is bound to their instance. For this case, Vue.js lifecycle hooks should not be declared as arrow functions.

Why not arrow functions?

Lifecycle hooks should be pure functions since arrow functions have their context entirely bound to their parent context.

Accessing data, methods and computed properties using this in arrow functions will throw an undefined error on the Vue.js instance.

Created hook

This lifecycle hook is called synchronously after the data has been created. This occurs before $el setup, but after data observation, computed properties, watch/event callbacks, and methods have been set up.

The created hook allows you to add code which is run if the Vue instance is created.

The steps in a Vue Lifecycle. are: beforeCreate, created, beforeMount, mounted, beforeUpdate, updated, beforeDestroy,destroyed.

At this point, the $el property is not yet accessible and is entirely unavailable.

So, when you need to run a particular function immediately when the data instance has been created, we can use this hook.

Also, to note that the created hook will only run once after the data, methods and computed properties have been set up.

Example

async created() { //Called synchronously after the instance is created try { const response = await fetch( `https://api.pexels.com/v1/search?query=cars&per_page=40` ); const data = await response.json(); console.log(data) } catch (error) { console.log(error); } }

In the examples shown above, we make a fetch API request to the endpoint and wait for a promise.

If the promise is resolved we simply log it to the console and in case of any error, we log it to the console too.

We can also attach async to created lifecycle hook to make asynchronous calls.

Note: Don’t use arrow functions on an options property or callback, such as created: () => console.log(this.a) or vm.$watch('a', newValue => this.myMethod()) . Since an arrow function doesn’t have a this , this will be treated as any other variable and lexically looked up through parent scopes until found, often resulting in errors such as Uncaught TypeError: Cannot read property of undefined or Uncaught TypeError: this.myMethod is not a function . vuejs.org

Conclusion

Just to recap that we have seen how the created lifecycle hook works and when to use it in our application.

It is advisable also to use it when we want to run a function once within our Vue.js application.

Thank you for reading through this article. If you found this piece helpful please do not hesitate to share it out.
V-Model ile Vue.js’de 2 Yönlü Veri İletişimi Nasıl Sağlanır?
By: Murat Umutlu
Tags: Two Way Data Binding, Vuejs

At the Intersection of the Development, Front-End, Back-End, and Mobile || JavaScript, Python, and AWS || murat@muum.dev
How to Deploy a Nuxt.js Project to the Server?
Tags: Vuejs, Nuxtjs, How To, Web Development, China

From Nuxt.js Official Website

What is Nuxt.JS

Nuxt.js is a lightweight application framework based on Vue.js. It can be used to create server-side rendering (Server Side Rendering, SSR) applications. It can also act as a static site generator (Static Site Generator, SSG) to generate static applications with features such as elegant code structure layering and hot loading

21YunBox provides a very simple Nuxt.js deployment method. You can deploy with 21YunBox in a static site environment or a Node environment.

How to Deploy Nuxt.js in China?

Register as 21YunBox member Fork Nuxt.js example on Gitee Create a cloud service on 21YunBox, and allow 21YunBox to access your code base Create with the following configuration:

If you’d like a step by step example, please refer to this example video.

Why 21YunBox

21YunBox is a Cloud Service Platform based out of Beijing, China. Our services provides you with an easy and budget friendly, end-to-end web platform deployment service within China for all applications. No matter your stack, we have a flexible solution to assist. If needed, we also offer full support in obtaining your ICP license which allows you to legally host online content within Mainland China.

To learn about the differences between 21YunBox and these foreign (outside of China) Cloud Service Platforms? You can refer to:
Adding Google Sign In for Vue.js app with AWS Amplify
By: Richard Yogaratnam
Tags: JavaScript, Amplify, AWS, Vuejs, Authentication

In this project lets add a social login , we will be adding a Google Sign In. Once you created and set up the vuejs project and initialized Amplify lets add the authentication.

amplify add auth

Do you want to use the default authentication and security configuration? Default configuration with Social Provider (F

ederation)

How do you want users to be able to sign in? Username

Do you want to configure advanced settings? No, I am done.

What domain name prefix do you want to use? authdemo

Next we have to add the URI you need to redirect after Sign In and Sign Up and select your social provider.



? Do you want to add another redirect signin URI No

Enter your redirect signout URI:

? Do you want to add another redirect signout URI No

Select the social providers you want to configure for your user pool: Google Enter your redirect signin URI: http://localhost:8080/ ? Do you want to add another redirect signin URIEnter your redirect signout URI: http://localhost:8080/ ? Do you want to add another redirect signout URISelect the social providers you want to configure for your user pool:

Before the next step we need to Sign in to your Google cloud console and create a new project. Next navigate to API and Services and select credentials.

Next select create credentials and select OAuth client ID.

Creating credentials

Next select web application for application type and select create. Once created you will be provided with the credentials.

credentials

we can now head back to the terminal enter the credentials .

Enter your Google Web Client ID for your OAuth flow: YOUR_CLIENT_ID

Enter your Google Web Client Secret for your OAuth flow: YOUR_CLIENT_SECRET

Next deploy your service.

amplify push

Are you sure you want to continue? Yes

Once completed copy the Hosted UI Endpoint and go to the google cloud console and edit the credentials created.

Add the copied endpoint to Authorized javascript origins and for the Authorized redirect URIs add https://<your_uri>/oauth2/idpresponse and click save.

And Finally lets open our vuejs app code and add the Sign In button.

App.vue

And now we can run the vue app. Voila!
GooglePay TypeScript VueJS — Playing Together.
By: Gopi Krishna Kancharla
Tags: Typescript, Vuejs, Google, Google Pay

GooglePay & TypeScript for a VUE component.

👉 This article is intended to write a Google Pay Button Integration with Vue JS. I am not posting any backend service intrgrations. As I see several people facing the issues for a quick integration extended the google provided javascript into a typescript, resulting in this quick write-up.

Points to catch:

Google Button click returns the “button” object for “this” reference. Not your component. So, make sure you get the singleton for processing further. If not, you will be seeing the below error as “is not a function”

<div no-gutters id="googleParent"> <div id="googleButtons"> <div id="google-button-container"></div> </div> </div>

Once integrated this is how the rendered button looks like.

Find other articles @ my publication: ThinkSpecial
Deploy VueJS with Nginx on sub-path
By: Temuujin Yavuuzandan
Tags: Vuejs, Vue, Vue Deploy, Nginx Vue Sub Path, Nginx Vue

A few days ago I had faced a problem with deploying the Vue project with Nginx on its sub-path. Deploying the Vue project on the root path is not a big problem but deploying it on a sub-path can be a nightmare(actually it took my 3 hours OMG).

So, I wanna share my experience with you guys. Hope this will save you precious night.

Let’s assume our domain will be hackum.com and we wanna deploy our Vue project on hackum.com/app path.

The first thing is first we have to change our Vue projects’s public path

Open vue.config.js file which is located in your Vue project. And change publicPath into your sub-path. For our example, it will be publicPath: ‘/app/’. The end slash is important don’t forget it.

publicPath: '/app/',

outputDir: 'dist',

assetsDir: 'static',

2. Build your project

The build command could be different based on your project config. But in most cases, it will be npm run build.

npm run build

You can find your build command from your packages.json. For my case, it will be npm run build:prod for production. If your config doesn’t have those don’t worry npm run build will work fine work you.

"scripts": {

"dev": "vue-cli-service serve",

"build:prod": "vue-cli-service build",

"build:stage": "vue-cli-service build --mode staging",

},

3. Nginx config

Open your Nginx site config which located in /etc/nginx/sites-available/

Then add those lines into the server block. Don’t forget to change the alias to your project directory

location /app {

alias /home/hackum/app/dist;

try_files $uri /index.html =404;

}

The last thing is to test our config and restart Nginx.

For the test, our config enters the following command.

sudo nginx -t

if everything is okay it will say ‘test is successful’ if not you have to fix a problem before restart it.

If everything is okay then restart Nginx with the following command.

sudo systemctl restart nginx

That's it, thank you for your attention. Hope this helps you.

My youtube channel
经由 CloudFlare 实现反向代理解决 vuejs 跨域问题的实践
By: Max Wang
Tags: Vuejs, Cloudflare, Proxy

经由 CloudFlare 实现反向代理解决 vuejs 跨域问题的实践

背景

vuejs 项目部署在 fake-a.com 上，需要请求位于 fake-b.com 上的 API，API 的 URL 类似 fake-b.com/api/items 。至于 fake-a.com 和 fake-b.com 这2个域名都经由 CloudFlare（简称“CF”）解析。

目标

在 fake-a.com 的 Apache 下开启反向代理，通过反向代理将发往 fake-a.com/api/items 的请求映射到 fake-b.com/api/items，这样就可以“欺骗”浏览器，允许 fake-a.com 上的 vuejs 项目调用 API 。

实现

首先，确保 Apache 开启了反向代理所需的模块。如果没有开启，可以参考文章《How To Use Apache as a Reverse Proxy with mod_proxy on Ubuntu 16.04》中提到的下列命令：

sudo a2enmod proxy

sudo a2enmod proxy_http

sudo a2enmod proxy_balancer

sudo a2enmod lbmethod_byrequests

依次执行上述命令后，记得重启 Apache 。

然后，编辑 fake-a.com 上 Apache 的 vhost conf 文件，比如：

/etc/apache2/sites-available/000-default.conf

其内容类似：

<VirtualHost *:80>

ServerAdmin webmaster@localhost

DocumentRoot /var/www/html <Directory /var/www/html/>

Options Indexes FollowSymLinks

AllowOverride All

Require all granted

</Directory> ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined <IfModule mod_dir.c>

DirectoryIndex index.html index.htm

</IfModule> </VirtualHost>

⚠️ 注意，因为在 fake-a.com 上只有一个项目，所以这个 vhost 配置文件中没有其它教程中出现的 ServerName 配置。如果你需要设置多个 vhost，那么可以自己添加，本文不牵扯这些内容。

在 vhost 中，只需添加如下内容：

添加后的完整 vhost 看起来应该是这样：



ServerAdmin webmaster@localhost

DocumentRoot /var/www/html



ProxyPass /api

ProxyPassReverse /api



<Directory /var/www/html/>

Options Indexes FollowSymLinks

AllowOverride All

Require all granted

</Directory> ServerAdmin webmaster@localhostDocumentRoot /var/www/htmlProxyPass /api http://fake-b.com/api ProxyPassReverse /api http://fake-b.com/api Options Indexes FollowSymLinksAllowOverride AllRequire all granted ErrorLog ${APACHE_LOG_DIR}/error.log

CustomLog ${APACHE_LOG_DIR}/access.log combined <IfModule mod_dir.c>

DirectoryIndex index.html index.htm

</IfModule>

</VirtualHost>

⚠️ 注意：在许多关于反向代理设置的教程中，往往会多一个命令 ProxyPreserveHost，即：



ProxyPass /api

ProxyPassReverse /api ProxyPreserveHost OnProxyPass /api http://fake-b.com/api ProxyPassReverse /api http://fake-b.com/api

如果设置了这一句，反向代理的请求就会被 CF 的安全机制拦截下来，触发一个 Error 1000 — DNS points to prohibited IP 错误。具体可以参考这个用户反馈。

结束。

另外，在 vuejs 项目中，常常还需要的解决一个问题是页面刷新后提示 404 Page Not Found，我个人倾向的解决办法是在站点的根目录下放置一个 .htaccess 文件，内容：

<IfModule mod_rewrite.c>

RewriteEngine On

RewriteBase /

RewriteRule ^index\.html$ - [L]

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . /index.html [L]

</IfModule>

上述配置也可以写在 vhost 配置中，但 .htaccess 更灵活。提示，记得为 Apache 开启 rewrite 模块，方法是：

a2enmod rewrite

记得重启 Apache 。
Life with Vue.js
By: Varun Kumar Medam
Tags: Development, Vuejs, Frontend, Developer

Most probably you are here to get to know how vue.js will works. So without making you bore let's dive into the world of vue 🏊

In fact, developers don't have time to try something that doesn't amaze them. ( I'll talk about testers later 😉 ). Instead of going with all the technical stuff in vue, I wanted to share Non-Technical and Interesting parts of it.

If you got a developer tag then you will definitely know about node.js, don't freak out if not. Of course, Vue.js is frontend but fully backed by the backend. Like everything Vue also depends on Node but poses like an independent framework 😜. I amazed when I am adding external plugins to my vue app using npm.

To be continued…
五分鐘搞懂Vue.js的技術定位-用更低的學習成本換取高效的前端實作能力
By: James Shieh
Tags: Front End Development, Vuejs

Find something more important than you are and dedicate your life to it.
Refactoring Electron Event-Driven Code.
By: Thomas Underwood
Tags: JavaScript, Front End Development, Vuejs, Electron, Nodejs

Refactored Vue mounted lifecycle hook.

In my last article, I wrote about how to build a Rsync GUI with Electron. With the incredible amount of responses to my previous article, I decided to continue to write more about my journey with Electron. The code I wrote for the Rsync client took about 2 hours to write and was in dire need of a refactor. If you want to catch up with where we are currently at feel, free to check out my last article below, otherwise let’s get going!

Let’s talk about the pre-refactored code and what can be improved. You will probably notice below that there is a bunch of ipcRenderer.on event listeners. There is also no naming convention or structure for the event names such as sync-complete, kill-sync, and sync-inprogress. Lastly, the scrollTo functionality is just awkwardly crammed into the sync-inprogress event listener.

Pre-refactored Rsync Vue Component

In the Electron Main Process Thread, you will notice some of the same issues that are present in the above Vue component. There are a couple of other issues as well. There is no set convention for the event response payloads and the code isn’t modular which would make reusability and testing easier.

Pre-refactored Main Electron Thread

In the refactored Vue component code a huge improvement was moving the event actions to an enum. This has many benefits: one place to reference and update, standardized event action names for both the front-end and back-end, and leads to cleaner code. You will also notice that all of the on event listeners were combined into a single generic event listener with a switch to control which event is executed. The same idea was also used for the event emitters. This leads to a cleaner, easier to read, and testable codebase. This is a similar kind of paradigm to Redux if you have ever used React. ScrollTo was also turned into its own function and payloads have a standardized form.

Refactored UI Code

Since the same event actions are used on both the front-end and back-end the same enum can be used in both places. This is handy and helps keep our code DRY and consistent between both the front and back end.

Event Actions Enum

The back-end Electron Main Process Thread was a piece of code that I was happy to refactor because the initial implementation was hasty and hard to reason about compared to this refactored code. You will notice that the functionality is a lot less tightly coupled and that most of the functionality is extracted to individual functions that are then called within the ipcMain.on event listener. Re-writing the code this way will lead to a much easier process when it comes to implementing unit tests when preparing the code for production.

Refactored Main Electron Process Thread

Thank you for joining me on this journey with Electron. I hope this article helps encourage you to try Electron for your next project! I will post more articles on how to implement more features with Electron soon. Stay tuned. If you found this article helpful please let me know!
Add Products for Ecommerce
By: Nil Madhab
Tags: JavaScript, Vuejs, Web Development, UI, Programming

Add Form

Let’s start with the add form. Here we will use the directives “v-on” and “v-show”. The “v-on” directive is used for listening to DOM events. This includes events like clicking, hovering, scrolling and many more. We will use this directive to listen to click events on the “Add a new product” button. On this click event, we can either perform some JavaScript logic or we can call some method of our component declared earlier. While calling the method, we can also pass arguments.

<button v-on:click=”addProductButtonPressed”> Add Product </button>

Vue also provides shortcuts for some directives. For example, “v-on” can be replaced with @ symbol.

<button @click=”addProductButtonPressed”> Add Product </button>

We will use the “v-show” directive to show the form for adding products. The “v-show” directive can be used to toggle the display of some HTML element based on some boolean condition. In the form, we will make use of the boolean variable showAddForm to decide whether to display the form or not.

Now in designing the form, we make use of the “v-model” directive. We can use this directive in the input fields of the form. This creates a two-way binding between the input fields and the data fields of our component. This way we can easily read the input values and even reset them when required.

<input type="text" placeholder="Enter name" v-model="tempName">

At the bottom of the form will be a submit button. Here also we will make use of the “v-on” directive to listen to the click event.
Using Vue CLI for Multi-Paged App Inside an ASP.NET Core Project
By: Munesh Kumar
Tags: Dotnet Core, Mpa, Aspnetcore, Vuejs

Not every app has to be an SPA, so; recently I came across a situation where I needed Vue.js for multi-paged app inside an ASP.NET Core project. Unfortunately, I couldn’t find anything that tackled this. Here is how I managed to do it. It might not be a best approach but it’s at least one of the way.

Before starting, I would mention here that this story will also help you to integrate Vue.js for SPA inside an ASP.NET Core project as well. I’ll tell you where to stop ;). So if you’re in this boat then go ahead.

I’m assuming that your ASP.NET Core project is already created and you’ve Vue CLI installed. And you’re using Visual Studio :)

Lets start with creating a simple Vue project. Open your console and go to your project directory and run below command.

When you run this command, it would probably ask for version. I’ve created using Default (Vue 2).

You should now end up with a structure like below. At this stage, the ‘dist’ folder will be missing at your end. Don’t worry ;)

Now go to your client-app folder and build your project. I’m using npm to build this project.

When you run this build, you would notice that the dist folder is created. But as we know with ASP.NET Project we need build results inside wwwroot. So, we’ll make some changes here. Create a new file inside client-app directory by name vue.config.js and mention the output directory.

Now when we build this project again we would end up in wwwroot directory. While we work we want our project to be rebuild automatically, so; lets add watch command inside package.json

Now if you run your ASP.NET Core project with ctrl+f5 , you would notice that you would also get your client-app’s build and it would ultimately slow down things. Instead you want this to happen only when deployment or publishing happens. So, lets tell MSBuild to do so.

If you’re looking for Vue SPA inside an ASP.NET Core project then you can stop your working here.

Lets start our implementation for MPA. Add pages section inside vue.config.js file. Each “page” should have a corresponding JavaScript entry file. For proper understanding, I’ve added two pages in my app.

You can read more about pages here.

And your directory should look like this

I hope you haven’t forgotten to build your client-app at this point. Now in order to call /products page you would need to create ASP.NET View. Let say your view path is ‘/Products/Index’ then inside your Index.cshtml add the following scripts.

Now run your ASP.NET project and go to ‘/Products/Index’. You would get your content rendered there…!

Conclusion

I know its not the perfect :) but it’s certainly a way to use Vue CLI with ASP.NET Core.

You can get the source here:

GitHub Repo

I’d love to hear any improvement/feedback :)
Simple Guide to Hosting Projects on Github.
By: Meet Raval
Tags: HTML, Vuejs, Github, Github Pages, React

Step-4: Settings [Final Step]

Go to the settings tab in Github.

Scroll down and find the Github Pages option in settings. And select a main branch or any other branch that you would like to publish and host online.

Then click save…

Then, just wait until GitHub does all the hard work…. Grab a cup of coffee or anything that you would snack on, after like 5 minutes refresh the github.

When you see the above thing rejoice and pat yourself on the back. Your site is published share the link to anyone, put it on Linkedin etc.. etc.

Enjoy …

What if you have REACT or Vue application to host on Github Pages.

I would suggest you take a good look at these websites as they have explained it much better than I can explain :)

To host REACT projects

To host Vue projects

To host Angular Projects

I hope you found the answer to the stuff that you are looking for. Stay Safe, Healthy & Happy.
How image src show the image from a blob/file
By: Alam Riku
Tags: JavaScript, Src, Vuejs, Laravel, Imagetag

this is how we get the blob/file data

Figure — 2 This is how we show a blob/file data onto a image tag using Javascript

Note: The blob’s result cannot be directly decoded as Base64 without first removing the Data-URL declaration preceding the Base64-encoded data. To retrieve only the Base64 encoded string, first remove data:*/*;base64, from the result.

The below part is for server side when have to deal with a blob file and base64 image file.

Use Case: Front-end on vue js and Back-end Laravel

upload a image from vue js to back-end server side Laravel.

vue js have to format the blob file to base64 format otherwise it can be send to server side back-end framework (laravel).

Figure-2 gives the script to get blob file as base64 image file.

If normal form submit is used to send the data to server side then don’t need to convert the image to base64.

this is how we can convert the base64 image file format to a png,jpg,gif, image file

I have used back-end as laravel.

Image::make() is a use case of intervention/image package for laravel.

Resources:

https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
來自倫敦的沉浸式數位表演-技術筆記之6
Tags: Vuejs, JavaScript, 沉浸數位表演

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Metadata-Driven Development using Vue 3
By: Prasad Jayakumar
Tags: JavaScript, Vuejs, How To, Beginner, Architecture

Application development lifecycle period got shrink to few weeks or couple of months. Visible outcomes are expected in every iterations.

For a simple CRUD based applications, low code or no code platforms seems to be attractive. I will provide the basics of Metadata-Driven Development, which could be a mid-path between hand-crafted “effective” web application development and low-code development.

Photo by Tina Witherspoon on Unsplash

Let’s say we need to create a basic form which allows a business user to capture daily exchange rates (CRUD form) to be utilized by their business process.

Basic CRUD form

Now, if we create this basic form by placing the exact controls and submission logic (by calling CRUD APIs) then this becomes a hand-crafted form.

Instead, if we create the same basic form with help of metadata (JSON or XMLs), then the approach is called metadata-driven development.
[Vuejs] 간단한 virtual scroll 만들기. Virtual scroll 을 적용해야 하는데, awesome vue에…
By: Dongmin Jang
Tags: Infinite Scroll, JavaScript, Vuejs, Vue, Virtualscroll

<template>

<div>

<span class="scroll">{{ scrollY }}</span>

<ul ref="list" :style="getStyle">

<li v-for="item of displayList" :key="item.index" :item="item.index">

[{{ item.name }}] {{ item.description }}

</li>

</ul>

</div>

</template> <script> export default {

name: 'HelloWorld',

data() {

return {

dummy: [],

sample: {

name: 'Tom',

description: 'Hellow world',

},

startIdx: 0,

endIdx: 10,

paddingTop: 0,

paddingBottom: 0,

scrollY: 0,

defaultHeight: 34,

}

},

created() {

for (let i = 0 ; i < 100; i++) {

this.dummy.push({

...this.sample,

index: i,

});

}

this.paddingBottom = this.defaultHeight * this.dummy.length - this.endIdx;

},

mounted() {

window.addEventListener('scroll', this.onScroll);

},

beforeDestroy() {

window.removeEventListener('scroll', this.onScroll);

},

computed: {

getStyle() {

return {

paddingTop: `${this.paddingTop}px`,

paddingBottom: `${this.paddingBottom}px`,

}

},

displayList() {

return this.dummy.slice(this.startIdx, this.endIdx);

}

},

methods: {

onScroll() {

this.scrollY = window.scrollY;

this.startIdx = Math.floor(this.scrollY / this.defaultHeight);

this.endIdx = Math.min(this.dummy.length, this.startIdx + 10);

this.paddingTop = this.defaultHeight * this.startIdx;

this.paddingBottom = this.defaultHeight * (this.dummy.length - this.endIdx);

}

}

}

</script>

<style scoped>

.scroll {

position: fixed;

top: 10px;

font-size: 20px;

font-weight: bold;

} ul {

list-style-type: none;

}

li {

display: block;

margin: 0 10px;

padding: 5px;

border: 1px solid red;

}

</style>

스크롤을 움직일 때마다 전체 리스트에서 노출할 부분에 대한 시작, 끝의 index를 계산합니다. 그리고 스크롤 방향에 따라 padding-top, bottom 을 계산해줍니다. 원리도 간단하고 실제 코드도 간단합니다.

물론 실제 프로젝트에서는 scroll to top 이나 중간 부터 노출되는 기능 등이 들어가서 여러가지 조건들을 고려한 수치들이 많이 들어갔고, 다양한 조건들을 고려해야 되서 구조 또한 훨씬 복잡합니다.

npm에서 virtual scroll을 가져다가 수정하려면 긴 코드들과 계산 로직들이 부담스러운데, 빠르고 가볍게 구현해보려고 시도해 본 내용을 남깁니다.
Vue JS, Paypal! Playing Together.
By: Gopi Krishna Kancharla
Tags: NPM, Typescript, PayPal, Front End Development, Vuejs

🚲 This article is intended to quickly show how to retrieve the PayPal button inside Vue JS Typescript enabled projects.

👉 Focus on the method “loadPaypal()”

The above code renders the screen that looks like in the below screenshot.
Create multiple custom checkboxes, bound to the same array - Vue 3 and Composition API
By: Kevin Bigelow
Tags: Tailwind Css, Vuejs, Vue 3, Font Awesome

In response to a comment on Build a checkbox component with Vue 3, Font Awesome, & Tailwind CSS

Single Checkbox 👈 Where the last article left off

👈 Where the last article left off Multiple Checkboxes 👈 Final code

Here’s a walkthrough of the main functional changes

Update the data in App.vue

setup() {

const names = ref([]);

return {

names,

};

},

2. The <check-box> component will now look like the snippet below, add as many as you want to App.vue . As you can see we’re also going to rename our label prop to value — this change makes sense since we’ll use the value passed for more than printing the label.

<check-box fieldId="Luther" v-model:names="names" value="Luther" />

3. Here’s what props should look like in checkbox.vue — changes are in bold. This component will receive the value (a single name), and an array of the checked names (bound to names in App.vue )

props: {

value: {

type: String,

required: true,

},

fieldId: {

type: String,

required: true,

},

names: {

type: Array,

required: true,

},

},

4. Checked is no longer a prop, we’ll determine checked with a computed property. All we have to do is check to see if value is in names

setup(props) {

const checked = computed(() => props.names.includes(props.value)); return {

checked,

};

},

5. Now we have to handle the checked functionality. With the single checkbox we just emitted checked — but since these checkboxes are bound to the names Array we need to add/remove our value from the list of names, and then emit the updated list. Let’s handle that with a method.

setup(props, context) {

const checked = computed(() => props.names.includes(props.value)); function check() {

// copy the names Array to avoid mutating props

let updatedNames = [...props.names];

// remove name if checked, else add name

if (this.checked) {

updatedNames.splice(updatedNames.indexOf(props.value), 1);

} else {

updatedNames.push(props.value);

}

// emit the updated names

context.emit("update:names", updatedNames);

} return {

check,

checked,

};

},

Don’t forget to call the method on @input

That should cover the main changes — everything is in that codesandbox

Thanks for the great question Jessie Green
Deploy a Nuxt.js Application to Netlify
By: John Philip
Tags: JavaScript, Netlify, Vuejs, Nuxtjs, Vue

In this article we are going to look on how we can deploy a static NuxtJs application to Netlify.

Netlify is a hosting website that provides free hosting and a faster way to build and deploy sites on the fly.

We will be deploying our application right from our GitHub repository.

Netlify is very convenient, in that after making changes to our application and pushing the code to GitHub we get the updated version of our application.

First things first we need to create a GitHub repository of our application that we will be deploying to Netlify.

After creating our repository, we need to log into the Netlify website and link our GitHub account.

If you do not have a Netlify account, you can sign up and create an account. After then you log in and you will be prompted to link either your GitHub, GitLab or Bitbucket account if you have any.
移り変わりの早いフロントエンドに対するスタディストの取り組み
By: Murata Katsuyasu
Tags: Vuejs, Frontend, Web Team, Storybook, Vue 3

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
為什麼資料更新了 DOM 卻沒有馬上改變？ Vue.nextTick 筆記
By: Eason Lin
Tags: Front End Development, Vuejs, JavaScript

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
How to copy to clipboard in Vue 3
By: Jamie Curnow
Tags: NPM, Front End Development, Vuejs, Open Source, Clipboard

Copy any text to the clipboard in Vue 3 with the new Vue composition API.

Photo by Kelly on Unsplash

TL;DR: Use vue-clipboard3 (I maintain this package)

Today I needed to copy some text to the clipboard in my new Vue app where I’m using Vue 3 and the composition api.

I didn’t want to use a Vue directive as this seems a little messy and not so declarative, and the existing solutions either don’t work in Vue 3, don’t have good typescript support, are used as a Vue plugin binding to ‘this’ or are a hack of a Vue 2 solution.

So I set about writing a new composable that uses the trusted clipboard.js under the hood, is fully typed, is simple and has no side effects, is declarative and easy to use, and follows the spirit of Vue 3 and the composition API.

It turned out to be extremely easy to make! I just installed clipboard.js and it’s types:

$ yarn add clipboard

$ yarn add --dev @types/clipboard

And make a single composable file

// composables/useClipboard.ts import Clipboard from 'clipboard' interface Options {

/** Fixes IE by appending element to body */

appendToBody: boolean

} export default (opts?: Options) => {

// default appendToBody true

const appendToBody = opts?.appendToBody === undefined ? true : opts.appendToBody

return {

toClipboard(text: string, container?: HTMLElement) {

return new Promise((resolve, reject) => {

// make fake element

const fakeEl = document.createElement('button')

// setup a new Clipboard.js

const clipboard = new Clipboard(fakeEl, {

text: () => text,

action: () => 'copy',

container: container !== undefined ? container : document.body

})

clipboard.on('success', (e) => {

clipboard.destroy()

resolve(e)

})

clipboard.on('error', (e) => {

clipboard.destroy()

reject(e)

})

// appendToBody fixes IE

if (appendToBody) document.body.appendChild(fakeEl)

// simulate click

fakeEl.click()

// remove from body if appended

if (appendToBody) document.body.removeChild(fakeEl)

})

}

}

}

Then in my Vue component I use it like this (simplified version):

<template lang="html">

<button @click="copy">Copy!</button>

</template>



<script lang="ts">

import { defineComponent } from '@vue/composition-api'

import useClipboard from '~/composables/useClipboard'



export default defineComponent({

setup() {

const { toClipboard } = useClipboard()



const copy = async () => {

try {

await toClipboard('Any text you like')

console.log('Copied to clipboard')

} catch (e) {

console.error(e)

}

}



return { copy }

}

})

</script>

Made something useful? Open-source it!

I figured this may be useful to a lot of people as we transition from Vue 2 to Vue 3 and the composition API. So I open-sourced it!

Now you can simply:

$ yarn add vue-clipboard3

And

import useClipboard from 'vue-clipboard3'

Check out the repo and examples here:

And if you find any problems or have any feature requests, drop me an issue on the repo:

Happy clipboarding! 📋
Ionic Vue CRUD Example App using Supabase.io, “The Open Source Firebase Alternative”
By: Clearly Innovative
Tags: JavaScript, Vuejs, Ionic, Tutorial, Programming

Looking for a firebase alternative…

I stumbled across Supabase.io a while ago but got interested again when I saw they just got 6M in funding so I figured I would take it for a spin and also do some live coding.

The website says: The Open Source Firebase Alternative Create a backend in less than 2 minutes. Start your project with a Postgres Database, Authentication, instant APIs, and real-time subscriptions.

Configuring Project

The video is here along with the source code. To get the project to work you will need your own credentials and then modify the config.js file
How to Deploy a VuePress Project to the Server?
Tags: Vuejs, Web Development, Vuepress, Static Site Generator, China

VuePress Official Website

What is VuePress

VuePress is a static site generator based on Vue. Can be used to make technical documents, personal blogs, etc.

21YunBox provides a very simple VuePress deployment method. You can deploy on the 21YunBox in a static site environment.

How to Deploy VuePress in China?

Register as a 21YunBox member In Gitee Fork VuePress Example Create a cloud service on 21YunBox, and allow 21YunBox to access your code base Create with the following configuration:

If the description of the above text is not clear, feel free to watch this step by step video.

Why 21YunBox

21YunBox is a Cloud Service Platform based out of Beijing, China. Our services provides you with an easy and budget friendly, end-to-end web platform deployment service within China for all applications. No matter your stack, we have a flexible solution to assist. If needed, we also offer full support in obtaining your ICP license which allows you to legally host online content within Mainland China.

To learn about the differences between 21YunBox and these foreign (outside of China) Cloud Service Platforms? You can refer to:
An Introduction to the Quasar Framework
By: Muhammad Anser
Tags: Quasar, JavaScript, Vuejs, Vue, Programming

Setting Up a Quasar Environment

Install Node after downloading from the official download link.

Install Quasar CLI by running:

npm install -g @quasar/cli

This command will do the necessary bootstrapping for you. It will ask a few questions, for which you can set your own priorities based upon the project’s requirements.

You can see the list of all the available commands by running Quasar on the terminal.

After the project is created successfully, go into the root folder and run:

quasar dev

You will be redirected to http://localhost:8080 and see the following:

Have a look at the folder structure, and you will see something like this:

Now open MainLayout.vue file and rename the app title to “My First Quasar App.” See if the change is reflected on the UI.

If everything goes perfectly, you should now see the name change reflected on the UI:

Awesome! It means that your first Quasar app is up and running. Go through the official docs and get your hands dirty with this awesome framework.
For Dummies: Vue.js Performance — Part 1
By: Luciano Buhler
Tags: JavaScript, Performance, Vuejs, Best Practices, Development

By participating in the first VueConf Toronto 2020 that took place today, while I listened to some of the main world names linked to Vue.js, including Evan You, the creator and leader of the Framework’s work, dealing with several specific themes, a common point between practically all the lectures caught my attention: performance.

As I am having the opportunity to work on the code review of some members of my team and I have identified a huge lack in how to put this fundamental UX theme into practice, not as senior experts with years and years of experience and with maximum degree in best practices, but as ordinary developers who want to do an excellent job. When looking at my bookshelf, a specific title caught my attention: ‘Basic Kitchen For Dummies’ (my wife bought it for me a few years ago, and maybe you should be wondering why this is. This is for another post.). Then I thought: why not?

Why For Dummies?

When using this terminology, ‘For dummies’, I do not do it in a pejorative way, but with the view that we, in the technical area, especially logical mathematics, have a tendency to assume that everyone who hears or reads us is obliged of understanding 100% of the subject and will automatically produce products, ideas, projects and codes at a level of excellence never seen before. However, this does not reflect reality.

So, when reading ‘For Dummies’, think of something written so that someone with minimal experience has the opportunity to understand and be able to apply and if you are already someone experienced in the subject, keep in mind the posture of someone who has humility to want to learn even if you are seeing something very simple and even banal. This is it!

About Performance

Performance refers to how well an activity or work is done. In terms of UX, this means above anything else: time and cost. The best possible result, at the lowest possible cost, in the shortest possible time. This is what we want when we try a service, whether virtual or not.

Notice that something done is very different from something well done. So, let me use an example from our daily lives to illustrate this concept of performance in a simple way.

When I was a kid I had classes from Monday to Saturday and a total of 12 subjects. Each day there were two or three different subjects and for each of these subjects I had a specific book and notebook.

Scenario 1: every day I took all notebooks and books, even if I used no more than 30% of the material.

Scenario 2: every day I took only the books and notebooks that would be needed that day.

Which of the two scenarios seems to make the most sense? Scenario 2 obviously. If we only consider executing Scenario 1, we can certainly be labeled as not very smart.

So why is it that when we program, most of us select Scenario 1 as the development approach?
Vue.js 核心概念 — 指令(2) V-ON is published by Sean Yeh.
By: Sean Yeh
Tags: JavaScript, Vuejs, Javascript Frameworks, Javascript Development, Vue

事件修飾符號

除了前面的preventDefault外，我們還可以使用其他事件修飾符號。官網說明書列出了下面幾個修飾符號的使用方式：

除了前面的preventDefault外，我們還可以使用其他事件修飾符號。官網說明書列出了下面幾個修飾符號的使用方式：

<!-- stop propagation --> <button @click.stop="doThis"></button>

這個stop修飾符號，可以在你想要阻止點擊事件傳布出去（propagating），避免在父元素上觸發這個事件時。

<!-- prevent default --> <button @click.prevent="doThis"></button>

使用這個prevent修飾符號，可以防止事件預設操作的執行。例如可以阻止在被點按時，傳送頁面的瀏覽。

<!-- prevent default without expression --> <form @submit.prevent></form>

只有修飾符號的情形。

<!-- chain modifiers --> <button @click.stop.prevent="doThis"></button>

修飾符號一次可以不只放一個，可以串連起來。

<!-- the click event will be triggered at most once --> <button v-on:click.once="doThis"></button>

要讓事件監聽器只在事件第一次發生時觸發時，可以使用這個once修飾符號。
Life cycle hooks in VueJS(2.x)
By: Mohd Daud Khan
Tags: Vuejs

Important points to remember

You can access data, computed properties, and methods inside life cycle hooks. You should not use an arrow function to define a lifecycle method. Mounting hooks are often the most-used hooks. They allow you to access your component immediately before and after the first render.

Lifecycle hooks(vue 2.x)

beforeCreate created beforeMount() mounted beforeUpdate updated activated deactivated beforeDestroy destroyed errorCaptured

When to use lifecycle hooks?

When you need to know when your component is created, added to the DOM, updated, or destroyed.
How to Deploy a Vue.js Project to a Server?
Tags: JavaScript, Vuejs, Web Development, China, Vue

Vue.js Official Website

What is Vue.js?

Vue (pronounced /vjuː/, similar to view) is a progressive JavaScript framework for building user interfaces. Unlike other large frameworks, Vue is designed to be applied layer by layer from the bottom up. Vue’s core library only focuses on the view layer, which facilitates integration with third-party libraries or existing projects.

21YumBox provides a very simple Vue.js deployment method. You can deploy on the 21YunBox in a static site environment.

How to Deploy Vue.js?

Register as a 21YunBox member In Gitee Fork Vue.js example Create a Cloud Service on 21YunBox, and allow 21YunBox to access your code base Create with the following configuration:

If you’d like a step by step example, please refer to this example video: How to deploy Vue.js to the server?

Why 21YunBox

21YunBox is a Cloud Service Platform based out of Beijing, China. Our services provides you with an easy and budget friendly, end-to-end web platform deployment service within China for all applications. No matter your stack, we have a flexible solution to assist. If needed, we also offer full support in obtaining your ICP license which allows you to legally host online content within Mainland China.

To learn about the differences between 21YunBox and these foreign (outside of China) Cloud Service Platforms? You can refer to:
Simple Calculator Just Using Properties in Vue JS [ Beginners]
By: Raja Tamil
Tags: Programming, Vuejs

This article demonstrates how easy it is to create a simple calculator in Vue JS just using the combination of regular and computed properties without using any events similar to the animation below.

In the vue template, declare four HTML elements.

<input> for number 1

<select> with four operands ( +, -, * , /) as options

<input> for number 2

<h2> for the result

<template>

<section>

<input placeholder="num1" type="number">

<select >

<option value="+"> + </option>

<option value="-"> - </option>

<option value="*"> * </option>

<option value="/"> / </option>

</select>

<input placeholder="num2" type="number" >

<h2></h2>

</section>

<template>

Then declare four properties inside this component, three inside the data() model and one will be a computed property.

<script>

export default {

data() {

return {

num1: 0,

num2: 0,

operand:""

};

},

}

</script>

Then bind these three properties to the input fields using a v-model directive with the number modifier except the operand property.

The number modifier will cast the value of num1 and num2 properties to a number so that we do not have to convert it outside of the template.

<input placeholder="num1" type="number" v-model.number="num1">

<select v-model="operand" >

<option value="+"> + </option>

<option value="-"> - </option>

<option value="*"> * </option>

<option value="/"> / </option>

</select>

<input placeholder="num2" type="number" v-model.number="num2">

There are multiple ways to implement the calculation, but the simplest way is to use a computed property.

A computed property is a great way to create new data from the existing properties declared in the data() model.

It also can be reactive and recompute any operation inside the computed property when any of the properties used inside have changed.

computed: {

result() {

switch(this.operand) {

case "+":

return this.num1 + this.num2

case "-":

return this.num1 - this.num2

case "*":

return this.num1 * this.num2

case "/":

return this.num1 / this.num2

}

}

}

Every time there will be data changed in the num1, num2 or operand properties, the result computed property will recalculate the num1 and num2 based on the operand and return an appropriate result.

Then we can use the result in the template.
Bootstrap-Vue ile Vue.js Form Validation
By: Haktan Sefa Pasin
Tags: Bootstrap Vue, Vuejs, Türkçe, Form Validation

not much, yet.
Unit Test Vue Composition Functions
By: An Xie
Tags: Jest, Unit Testing, Composition Api, Vuejs, Vue 3

At my current work, we are trying to migrate the vue2 project to use composition API. One question that came up from my co-worker is can we still mock the composition function easily like what we did for services classes. That is a very good question, but I don't see anything that could block us to mock it. First of all, the class is just syntax sugar for functions in JS. Secondly, the Vue composition function is just a regular JS factory function that returns a bunch of Vue specifically stuff like refs, etc.

From what I research on the internet/discord/github, I didn’t find any example to test a composition function. Even in some Vue composition functions library (my favorite VueUse for example) tests for functions are missing. Write your unit test guys!!!

TLDR, here is the code of how you do it:

Leave a comment if you got any questions on this.