diferenence between javascript and vuejs

in vs code 

create one html file

shift 1

tab

it wil create automatic vue boiler plate

install live server in vs code 


open ur html page

right click 

open with live server
apps( quiz,notes,crud,ecommerce)

counter

varia

in javascript

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter App</title>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
text-align: center;
margin-top: 50px;
}
.counter {
font-size: 24px;
margin-bottom: 20px;
}
.btn {
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
}
</style>
</head>
<body>
<div class="container">
<div class="counter" id="counter">0</div>
<button class="btn" onclick="increment()">Increment</button>
<button class="btn" onclick="decrement()">Decrement</button>
<button class="btn" onclick="reset()">Reset</button>
</div>

<script>
let count = 0;
const counterElement = document.getElementById('counter');

function increment() {
count++;
counterElement.textContent = count;
}

function decrement() {
if (count > 0) {
count--;
counterElement.textContent = count;
}
}

function reset() {
count = 0;
counterElement.textContent = count;
}
</script>
</body>
</html>
===


variable declarations => const thing,

we can cal it also state

if state change => 

vuejs

===

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Counter App with Vue.js</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<style>
body {
font-family: Arial, sans-serif;
}
.container {
text-align: center;
margin-top: 50px;
}
.counter {
font-size: 24px;
margin-bottom: 20px;
}
.btn {
padding: 10px 20px;
font-size: 18px;
cursor: pointer;
}
</style>
</head>
<body>
<div id="app" class="container">
<div class="counter">{{ count }}</div>
<button class="btn" @click="increment">Increment</button>
<button class="btn" @click="decrement">Decrement</button>
<button class="btn" @click="reset">Reset</button>
</div>

<script>
new Vue({
el: '#app',
data: {
count: 0
},
methods: {
increment() {
this.count++;
},
decrement() {
if (this.count > 0) {
this.count--;
}
},
reset() {
this.count = 0;
}
}
});
</script>
</body>
</html>

====

npm init vue@latest



our applcation is depenedent on these dependenicies

to run our application we have ot install this application 

it maybe with boiler plate or after completed our application  "dependencies": {

"@fortawesome/fontawesome-free": "^6.5.1",
"@fortawesome/fontawesome-svg-core": "^6.5.1",
"@fortawesome/free-solid-svg-icons": "^6.5.1",
"@fortawesome/vue-fontawesome": "^3.0.6",
"bootstrap-vue-3": "^0.5.1",
"bootstrap-vue-next": "^0.16.6",
"core-js": "^3.8.3",
"vue": "^3.4.21",
"vue-router": "^4.3.0",
"vuex": "^4.1.0"
},
"devDependencies": {
"@babel/core": "^7.12.16",
"@babel/eslint-parser": "^7.12.16",
"@vue/cli-plugin-babel": "~5.0.0",
"@vue/cli-plugin-eslint": "~5.0.0",
"@vue/cli-service": "~5.0.0",
"eslint": "^7.32.0",
"eslint-plugin-vue": "^8.0.3",
"vue-loader": "^17.4.2",
"vue-template-compiler": "^2.7.16"
},


after installation of boiler plate 

we have to run npm install 

then it will download from cloud to our machine

whatever downloaded packages we can see at node_modules

after install


npm run serve or npm run dev


whatever commands run that will be there in packages.json scripts 

"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"lint": "vue-cli-service lint"
},


<button >+</button>

add lisetener to this button  may be action the button

<button @click="function name">+</button>

"" => in quotes => strings 

v-on:click

on + click => it will update the count means re render that respective html  ( in javasript for every rerender => it slow down the page)

const count =0 or const count = ref(0);

console.log(count);



click event handler

<script setup > in compositon api

<script> in options api

its is old  one


compositon api

looks cleaner script

pure script or pure javascript

it is future ( use this only)

what is directives

directives are instructions for vue to do certain things

@click ="showmodal=true"

v-show="showmodal"


v-modal => 

bidirectional directive

 means it takes from user input and 

it takes from varaible 


v-for key is 

one unique may be id

style with colon means its changing na forevery loop 

this is the reason

 



error handling 


errormessage.value="showing error"

notes page

<script setup>
  import {ref} from "vue";

  const showModal = ref(false)
  const newNote = ref("");
  const errorMessage = ref("")
  const notes = ref([]);

  function getRandomColor() {
    return "hsl(" + Math.random() * 360 + ", 100%, 75%)";
  }

  const addNote = () => {
    if(newNote.value.length < 10) {
      return errorMessage.value = "Note needs to be 10 characters or more"
    }
    notes.value.push({
      id: Math.floor(Math.random() * 1000000),
      text: newNote.value,
      date: new Date(),
      backgroundColor: getRandomColor()
    });
    showModal.value = false;
    newNote.value = ""
    errorMessage.value = ""
  }

</script>

<template>
  <main>
    <div v-if="showModal" class="overlay">
      <div class="modal">
        <textarea v-model.trim="newNote" name="note" id="note" cols="30" rows="10"></textarea>
        <p v-if="errorMessage">{{errorMessage}}</p>
        <button @click="addNote">Add Note</button>
        <button class="close" @click="showModal = false">Close</button>
      </div>
    </div>
    <div class="container">
      <header>
        <h1>Notes</h1>
        <button @click="showModal = true">+</button>
      </header>
      <div class="cards-container">
        <div 
          v-for="note in notes"
          :key="note.id"
          class="card" 
          :style="{backgroundColor: note.backgroundColor}"
        >
          <p class="main-text">{{ note.text }}</p>
          <p class="date">{{ note.date.toLocaleDateString("en-US") }}</p>
        </div>
      </div>
    </div>
  </main>
</template>

<style scoped>
  main {
    height: 100vh;
    width: 100vw
  }

  .container {
    max-width: 1000px;
    padding: 10px;
    margin: 0 auto
  }

  header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  h1 {
    font-weight: bold;
    margin-bottom: 25px;
    font-size: 75px;
  }

  header button {
    border: none;
    padding: 10px;
    width: 50px;
    height: 50px;
    cursor: pointer;
    background-color: rgb(21,20,20);
    border-radius: 100%;
    color: white;
    font-size: 20px;
  }

  .card {
    width: 225px;
    height: 225px;
    background-color: rgb(237, 182, 44);
    padding: 10px;
    border-radius: 15px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-right: 20px;
    margin-bottom: 20px;
  }

  .date {
    font-size: 12.5px;
    font-weight: bold;
  }

  .cards-container {
    display: flex;
    flex-wrap: wrap;
  }

  .overlay {
    position: absolute;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.77);
    z-index: 10;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .modal {
    width: 750px;
    background-color: white;
    border-radius: 10px;
    padding: 30px;
    position: relative;
    display: flex;
    flex-direction: column;
  }

  .modal button {
    padding: 10px 20px;
    font-size: 20px;
    width: 100%;
    background-color: blueviolet;
    border: none;
    color: white;
    cursor: pointer;
    margin-top: 15px
  }

  .modal .close {
    background-color: rgb(193, 15, 15);
    margin-top: 7px;
  }

  .modal p {
    color: rgb(193, 15, 15);
  }
</style>

component and props


import data from data.json

const quizzes = ref(q);

const search = ref("");

it is search state

if it is not empty=> we have to run the login

means continuosly monitoring the state changes or not 

for that we have to import watch or compouted

if it is large logic => we have to use watch

watch(search,()=>{

console.log("hello");

});

watch(search,()=>{

quizes.value=data.filter(quiz=>quiz.name.tolowercase().includes(search.value.tolowercase);

});


import {defineProps} from vue;

const {quiz} = defineProps(['quiz]);

console.log(quiz);


pagination and routing

quizzes 

click on section 

answer questions

redirect to if correct all are corect


at css file

@import "./base.css";


app.vue

import {routerview} from 'vue-router";

<routerview/>

router link has

inbuilt prop is 

active-class="active"

dynamic routes

extract the route params

import {useroute} from vue-router;

const route = useROUTE();

route.params.id;



nested routes

car/21/contact

children


404 not found

path:"/:catchall(.*)*"

https://router.vuejs.org/guide/essentials/dynamic-matching

{ path: '/:pathMatch(.*)*', name: 'NotFound', component: NotFound }, // will match anything starting with `/user-` and put it under `route.params.afterUser` { path: '/user-:afterUser(.*)', component: UserGeneric }, ]


redirect 

{

path:"home"

redirect:"/",

}

quiz app

const questionstatus = ref(`${current.value}/${variable}`); ( decalared state)

watch(()=>currentquesitonindx.value,()=>{questionstatus.value=`${current.value}/${variable}` });



(listener)

above equalt to computed

const questionStatus = computed(()=>{

return '${curentquestionindex.value}/${quiz.questions.length}';

});

const questionStatus = computed(()=> '${curentquestionindex.value}/${quiz.questions.length}');

instead of declaring state and definign wathc function, we can write as computed function if we wanna observer changes


more computing

 const questionStatus = computed(()=> '${curentquestionindex.value/quiz.questions.length}');

we can pass multiple prps to a acomponent

define multiple props
const {var1,var2}= definePRops(["var1","var2"])

child to parent emit 

const emti =defineEmits('selectOPtin');

const emtiselectedoption=(argument)=>{}

api


front end put a request to api and it will process this request and fetch data from database

https://breakingbadapi.com/api/characters

https://breakingbadapi.com/api/episodes

https://breakingbadapi.com/api/quote/random


const fetchcarhater = async()=>{

const response = await axios.get('');

}

<suspense> is a inbuitl component


default is top level async

fallback is loader

async =. if loading it showis loader, if loads,it gets the data

npm i -D naiviui


like boostrap vue

https://www.naiveui.com/en-US/os-theme/components/notification



watch(page,async()=>{

const res= await axios.get();

characters.value = res.data;

});

https://vuejs.org/api/composition-api-lifecycle


onuodated means 

state is update 

which life cycle hook we showuld use 

onbeforemounted

onupdated

computed

mounted

rickandmortyapi.com 

https://rickandmortyapi.com/documentation



<keepalive> is inbult component 

rerender automatically



states in vue

declare state with reactive



const color = reactive({read:0,});

ref is type any => object, boolean

reactive type object it takes object only



ref access state with .value()
reactive accsss state directly

lot of nested components 
div.line tag div class="lane"
declared numbers state in app.vue, passing from paretn to greate grend child step by step via props

app.vue declared numbers tate
in parent component taken from appvue using props
in child taken from parent using props 
in grand child taken from child using props that same number state
in greate grand child taken from grand child using props from the same number state

provide inject in nested components
in app.vue
const numbers = ref([1,2,3,4,5,6]);
provide("numbers",numbers); ====> upload

child.vue



    import {inject} from "vue";
const numbers = inject("numbers");


const addnumber= (num)=> {
numbers.value.push(num)
}
provide inject is like eventbus in vuejs

https://vuejs.org/guide/reusability/composables

reusability 

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'

const x = ref(0)
const y = ref(0)

function update(event) {
x.value = event.pageX
y.value = event.pageY
}

onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))
</script>

<template>Mouse position is at: {{ x }}, {{ y }}</template>


But what if we want to reuse the same logic in multiple components? We can extract the logic into an external file, as a composable function:

// mouse.js
import { ref, onMounted, onUnmounted } from 'vue'

// by convention, composable function names start with "use"
export function useMouse() {
// state encapsulated and managed by the composable
const x = ref(0)
const y = ref(0)

// a composable can update its managed state over time.
function update(event) {
x.value = event.pageX
y.value = event.pageY
}

// a composable can also hook into its owner component's
// lifecycle to setup and teardown side effects.
onMounted(() => window.addEventListener('mousemove', update))
onUnmounted(() => window.removeEventListener('mousemove', update))

// expose managed state as return value
return { x, y }
}

=

<script setup>
import { useMouse } from './mouse.js'

const { x, y } = useMouse()
</script>

<template>Mouse position is at: {{ x }}, {{ y }}</template>

create folder called composables (like mixins.js )

composables/usenumbers.js







const (numbers,addnumber} = usenumbers();
@click="addnumber()"



global state with pinia



https://pinia.vuejs.org/introduction.html#Why-should-I-use-Pinia-
https://www.vuemastery.com/dashboard

npm install pinia

go to root and create stores folder
stores/numbers.js

// stores/counter.js
import { defineStore } from 'pinia'

export const useCounterStore = defineStore('counter', {
state: () => {
return { count: 0 }
},
// could also be defined as
// state: () => ({ count: 0 })
actions: {
increment() {
this.count++
},
},
})
import {storetorefs} from 'pinia';


h

And then you use it in a component:

<script setup>
import { useCounterStore } from '@/stores/counter'
const counter = useCounterStore()
counter.count++
// with autocompletion ✨
counter.$patch({ count: counter.count + 1 })
// or using an action instead
counter.increment()
</script>
<template>
<!-- Access the state directly from the store -->
<div>Current Count: {{ counter.count }}</div>
</template>


main.js






written in stores and import where we required likestate management (option api )

getters

return {numbers,addNUmber,flterNum};


getters

import at required component 



scroll based pagination 
intersection observe api 
https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

new Intersexctionobserver 
default javascript fun

dom element is observer 
just observer that



if entry and entry.intesecting







v-if posts.length


===


No comments:

Post a Comment

Event listening in react

 How we can listen to som eevents some envents fire like click or automatically user enters into input button , that is event on word type i...