Categories
Vue 3 Projects

Create a Drag and Drop App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a drag and drop app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create drag-and-drop

and select all the default options to create the project.

Create the Drag and Drop App

To create the drag and drop app, we write:

<template>
  <h2>Draggable Elements</h2>
  <div
    class="draggable"
    :draggable="true"
    @dragstart="drag($event, o)"
    v-for="o of origin"
    :key="o"
    @click.stop
  >
    {{ o }}
  </div>

<h2>Target</h2>
  <div id="target" @dragover.prevent @drop="drop">
    <div class="draggable" v-for="t of target" :key="t">
      {{ t }}
    </div>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      origin: ["apple", "orange", "grape"],
      target: [],
    };
  },
  methods: {
    drag(ev, text) {
      ev.dataTransfer.setData("text", text);
    },
    drop(ev) {
      const text = ev.dataTransfer.getData("text");
      const index = this.origin.findIndex((o) => o === text);
      this.origin.splice(index, 1);
      this.target.push(text);
    },
  },
};
</script>

<style scoped>
.draggable {
  border: 1px solid black;
  margin-right: 5px;
}

#target {
  border: 1px solid black;
  width: 95vw;
  height: 100px;
  padding: 5px;
}
</style>

In the template, we have divs under the Draggable Elements heading.

We style the divs by setting the class of each div to draggable .

Then we add a border to the draggable class.

To make the divs draggable, we set the draggable prop to true .

Next, we add the @dragstart directive to listen for the dragstart event, which is triggered when we first start dragging the div.

We use v-for to render the items in the origin array.

And we set the key to the origin entry so that Vue 3 can identify the items.

The entries are unique so we can just assign them as the value of the key prop.

Also, we have the @click.stop directive to stop the propagation of the click event.

Below the Target heading, we have the container div for the draggable items.

We have the @dragover.prevent directive to prevent the default behavior when we drag over the div which lets us keep dragging the item.

The @drop directive lets us call drop to put the items in the target array.

We render the target array inside the div with ID target with v-for .

In the script tag, we have the data method which has the origin and target reactive properties.

The drag method calls ev.dataTransfer.data to set the data we’re transferring when we start dragging the element.

In the drop method, we call ev.dataTransfer.getData to get the data by the key and return the item with key 'text' .

Then we find the item in the origin array and remove it from it with splice .

Then finally, we call this.target.push to append the item to the target array.

The style tag has some styles for the draggable items and the target container div.

Now we can drag the items from the Draggable Elements section to the Target section.

Conclusion

We can add drag and drop features easily into our app with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a JSON to CSV Converter with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a JSON to CSV cowith Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create json-to-csv

and select all the default options to create the project.

Create the JSON to CSV Converter

To create the JSON to CSV converter, we write:

<template>
  <form @submit.prevent="convert">
    <div>
      <label>json</label>
      <textarea v-model="json"></textarea>
    </div>
    <button type="submit">convert</button>
  </form>
  <div>
    <label>csv</label>
    <textarea v-model="csv"></textarea>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      json: "",
      csv: "",
    };
  },
  methods: {
    convert() {
      const parsedJson = JSON.parse(this.json);
      if (
        !Array.isArray(parsedJson) ||
        !parsedJson.every((p) => typeof p === "object" && p !== null)
      ) {
        return;
      }
      const heading = Object.keys(parsedJson[0]).join(",");
      const body = parsedJson.map((j) => Object.values(j).join(",")).join("n");
      this.csv = `${heading}${body}`;
    },
  },
};
</script>

In the template, we have a form that takes the JSON array string.

The textarea in the form has v-model to bind the inputted value to the json reactive property.

The form element has the @submit directive to listen to the submit event which is triggered when we click convert.

prevent lets us do client-side form submission instead of server-side.

Below that, we have a div to display the CSV result in the textarea.

We bind it to the csv reactive property with v-model .

In the script tag, we have the data method to return the reactive properties.

Then in the convert method, we parse the json string with JSON.parse .

And then we check if the parsed object is an array and that all entries are objects.

Then we create the heading from the keys of the first entry.

We get the keys with Object.keys .

Then we get all the values with Object.values and the join them together with commas with join .

And we join the rows together with join and a new line character as the argument.

Finally, we assign a string with heading and body combined to this.csv to display the result in the 2nd textarea.

Conclusion

We can create a JSON to CSV converter with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Weather App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a weather app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create weather-app

and select all the default options to create the project.

Create the Weather App

To create the weather app, we write:

<template>
  <form @submit.prevent="getWeather">
    <div>
      <label>city</label>
      <input v-model.trim="city" />
    </div>
    <button type="submit">get weather</button>
  </form>
  <div>
    <p>feels like: {{ result.feels_like }}</p>
    <p>humidity: {{ result.humidity }}</p>
    <p>pressure: {{ result.pressure }}</p>
    <p>temperature: {{ result.temp }}</p>
    <p>high: {{ result.temp_max }}</p>
    <p>low: {{ result.temp_min }}</p>
  </div>
</template>

<script>
const APIKEY = "your-key";

export default {
  name: "App",
  data() {
    return {
      city: "",
      result: {},
    };
  },
  methods: {
    async getWeather() {
      if (!this.city) {
        return;
      }
      const res = await fetch(
        `https://api.openweathermap.org/data/2.5/weather?q=${this.city}&appid=${APIKEY}`
      );
      const { main } = await res.json();
      this.result = main;
    },
  },
};
</script>

We have a form with an input that lets us enter the city.

We bind the inputted value to the city reactive property with v-model .

The trim modifier lets us remove the leading and trailing whitespace with the inputted value.

The @submit directive lets us listen to the submit event which is triggered when we click the get weather button.

prevent lets us prevent server-side submission and do a client-side submission.

Below that, we display the result from the response.

In the script tag, we have the data method to return reactive properties.

The getWeather method calls fetch to make a request to the Open Weather Map API to get the weather data based on the entered city .

And then we call res.json to convert the response to a JavaScript object.

Finally, we assign that to this.result so we can display it in the template.

Conclusion

We can create a weather app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Voting App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a voting app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create voting-app

and select all the default options to create the project.

Create the Voting App

To create the voting app, we write:

<template>
  <form>
    <div>
      <label>What's your favorite fruit?</label>
      <input type="radio" value="apple" v-model="choice" /> apple
      <input type="radio" value="orange" v-model="choice" /> orange
      <input type="radio" value="grape" v-model="choice" /> grape
    </div>
    <button type="button" @click="vote">vote</button>
  </form>
  <div>
    <h1>result</h1>
    <p v-for="(value, key) of results" :key="key">{{ key }}: {{ value }}</p>
  </div>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      choice: "",
      results: {},
    };
  },
  methods: {
    vote() {
      if (!localStorage.getItem("vote-result")) {
        localStorage.setItem("vote-result", JSON.stringify({}));
      }
      const { choice } = this;
      const results = JSON.parse(localStorage.getItem("vote-result"));
      if (!Object.prototype.hasOwnProperty.call(results, choice)) {
        results[choice] = 0;
      }
      results[choice]++;
      localStorage.setItem("vote-result", JSON.stringify(results));
      this.results = JSON.parse(localStorage.getItem("vote-result"));
    },
  },
};
</script>

In the template, we have the form with radio buttons that binds to the choice reactive property with v-model .

The vote button runs the vote method when it’s clicked.

The div renders the choices and the number of votes for each.

value has the number of votes.

key has the choice name.

In the script tag, we have the data method that returns the reactive properties we’re using.

In the vote method, we check if the local storage result with key vote-result exists.

If it doesn’t we call setItem to add the entry.

Then we get the result by calling getItem with vote-result and parse the returned string with JSON.parse .

Then we check if the choice exists in the result.

If Object.prototype.hasOwnProperty.call(results, choice) returns true , then the property for the choice exists in results .

If it doesn’t, we add the property and set it to 0.

And then we increment the property’s value by 1 to register the vote.

Then we call setItem to update the local storage entry.

And then we get it and parse it again and assign that to this.results to update it.

Conclusion

We can create a voting app easily with Vue 3 and JavaScript.

Categories
Vue 3 Projects

Create a Drawing App with Vue 3 and JavaScript

Vue 3 is the latest version of the easy to use Vue JavaScript framework that lets us create front end apps.

In this article, we’ll look at how to create a drawing app with Vue 3 and JavaScript.

Create the Project

We can create the Vue project with Vue CLI.

To install it, we run:

npm install -g @vue/cli

with NPM or:

yarn global add @vue/cli

with Yarn.

Then we run:

vue create drawing-app

and select all the default options to create the project.

Create the Drawing App

To create the drawing app, we write:

<template>
  <canvas
    ref="canvas"
    @mousemove="draw"
    @mousedown="setPosition"
    @mouseenter="setPosition"
    @resize="resize"
    id="canvas"
  ></canvas>
</template>

<script>
export default {
  name: "App",
  data() {
    return {
      pos: {},
    };
  },
  methods: {
    setPosition(e) {
      this.pos.x = e.clientX;
      this.pos.y = e.clientY;
    },
    resize() {
      const { canvas } = this.$refs;
      const ctx = canvas.getContext("2d");
      ctx.canvas.width = window.innerWidth;
      ctx.canvas.height = window.innerHeight;
    },
    draw(e) {
      if (e.buttons !== 1) {
        return;
      }
      const { canvas } = this.$refs;
      const ctx = canvas.getContext("2d");
      const { pos } = this;
      ctx.beginPath();
      ctx.lineWidth = 5;
      ctx.lineCap = "round";
      ctx.strokeStyle = "green";
      ctx.moveTo(pos.x, pos.y);
      this.setPosition(e);
      ctx.lineTo(pos.x, pos.y);
      ctx.stroke();
    },
  },
};
</script>

<style scoped>
#canvas {
  border: 1px solid black;
}
</style>

In the template, we add the canvas element.

We assign it a ref so that we can access the component code.

Also, we add a few event listeners to the canvas.

mousemove listens to mouse movements and draw on the canvas when we move the mouse.

mousedown and mouseenter events are triggered when we click on a mouse button or enter the canvas respectively, so we set the position to start drawing the line.

The resize event is triggered when we change the screen size, and we need to listen to that to change the canvas size to match the screen.

In the script tag, we have the data method that returns the pos reactive property that we use to store the mouse position.

The setPosition method sets this.pos to the current position of the mouse.

The resize method gets the canvas and set the width and height of the canvas respectively.

We resize it so that the mouse position matches the canvas position when we draw.

The draw method does the drawing.

We only draw when we click on the left mouse button, and we check that by checking if e.buttons is 1.

Then we get the canvas and the mouse position from this.pos .

We call beginPath to start drawing.

lineWidth sets the line width.

lineCap sets the line end style.

strokeStyle sets the color of the line.

moveTo moves the cursor to the given position.

lineTo draws the line to the given position.

stroke renders the line drawn.

In the style tag, we set the border so that we can see where the canvas is.

Conclusion

We can create a drawing app easily with Vue 3 and JavaScript.