#vue pass data from parent to child
Explore tagged Tumblr posts
dsjghkbvkdj · 5 months ago
Text
Understanding Slots in Vue
Tumblr media
Slots serve as placeholders within a child component's template where parent components can insert their own content. This mechanism promotes component reusability and adaptability. There are different types of slots in Vue:
Default Slots: Allow the parent to pass content without a specific name.
Named Slots: Enable the parent to pass content to designated slots identified by names.
Scoped Slots: Provide a way for child components to pass data back to the parent through the slot, allowing the parent to render content based on that data.
Using Slots in <script setup>
With the introduction of the <script setup> syntax in Vue 3, handling slots has become more streamlined. The <script setup> is a compiler macro that allows you to write less boilerplate code when using the Composition API. To work with slots inside <script setup>, Vue provides the useSlots() and useAttrs() helper functions.
The useSlots() function returns an object containing all the slots passed to the component, which can be utilized within the <script setup> block. This is particularly useful when you need to programmatically interact with the slots.
vue
CopyEdit
<script setup> import { useSlots } from 'vue'; const slots = useSlots(); // You can now use `slots` to access the slots passed to this component </script>
In scenarios where you need to provide type hints for slots, especially when using TypeScript, Vue 3.3 introduced the defineSlots() macro. This macro allows you to define the expected slots and their props, enabling better type checking and editor support.
vue
CopyEdit
<script setup lang="ts"> const slots = defineSlots<{ default: (props: { msg: string }) => any; header: (props: { title: string }) => any; }>(); </script>
By defining slots in this manner, you enhance the maintainability and readability of your components, making it clear what slots are expected and what props they provide.
Practical Example
Let's consider a practical example where we have a BaseLayout component that utilizes named slots to structure a page layout:
vue
CopyEdit
<template> <div class="container"> <header> <slot name="header"></slot> </header> <main> <slot></slot> <!-- default slot --> </main> <footer> <slot name="footer"></slot> </footer> </div> </template>
In the parent component, we can use the BaseLayout and provide content for each slot:
vue
CopyEdit
<template> <BaseLayout> <template #header> <h1>Page Title</h1> </template> <template #default> <p>This is the main content of the page.</p> </template> <template #footer> <p>© 2025 My Website</p> </template> </BaseLayout> </template>
In this example, the BaseLayout component defines three slots: header, default, and footer. The parent component then provides the content for each slot using the v-slot directive (shorthand #). This approach allows for a clean and organized way to compose layouts with reusable components.
Conclusion
Mastering the use of slots in Vue, particularly within the <script setup> syntax, empowers developers to create flexible and maintainable components. By effectively leveraging default, named, and scoped slots, you can build complex user interfaces that are both reusable and easy to manage. Understanding how to use slots in scripts is essential for any Vue developer aiming to write clean and efficient code.
more details : vue how to use slots in script
0 notes
qaujdhfbmndm21 · 5 months ago
Text
Mastering Scoped Slots in Vue 2: A Complete Guide
Tumblr media
Vue.js is a progressive framework that offers developers numerous features to build dynamic and interactive web applications. One of its most powerful features is scoped slots, which enable flexible and reusable component patterns. This article will explain how to access scoped slots in Vue 2, empowering you to create highly customizable components.
What Are Scoped Slots?
Scoped slots in Vue 2 are an advanced slot mechanism that allows a parent component to pass data to a child’s slot content. Unlike regular slots, scoped slots provide a way to dynamically inject content into components based on specific data from the child component.
For instance, imagine a table component where you want to customize the content of each cell dynamically. Scoped slots make this possible.
How to Access Scoped Slots in Vue 2?
To understand how to access scoped slots in Vue 2, follow these steps:
Define the Scoped Slot in the Child ComponentThe first step is to define a scoped slot in your child component. For example:vueCopy code<template>
  <div>
    <slot :info="dataFromChild"></slot>
  </div>
</template>
<script>
export default {
  data() {
    return {
      dataFromChild: "Hello from child component!"
    };
  }
};
</script>
Here, the slot element passes the dataFromChild property to the parent via the info attribute.
Access the Scoped Slot in the Parent ComponentIn the parent component, use the v-slot directive to bind the slot scope:vueCopy code<template>
  <ChildComponent v-slot="{ info }">
    <p>{{ info }}</p>
  </ChildComponent>
</template>
The { info } syntax extracts the scoped data, which you can then use within the slot’s content.
Dynamic Content RenderingScoped slots are incredibly useful for rendering dynamic content. For example, you can loop through an array of data and use scoped slots to display each item:vueCopy code<template>
  <ChildComponent v-slot="{ info }">
    <ul>
      <li v-for="(item, index) in info" :key="index">{{ item }}</li>
    </ul>
  </ChildComponent>
</template>
Here, the info object can contain a list of items that the parent renders dynamically.
Practical Use Cases
Understanding how to access scoped slots in Vue 2 unlocks several possibilities:
Customizable TablesBuild dynamic table components where each column’s content can be customized based on the data.
Reusable UI ComponentsCreate components like modals or dropdowns where the content is determined by the parent component.
Flexible LayoutsUse scoped slots to define layouts where the structure is consistent, but the content varies.
Tips for Using Scoped Slots Effectively
Keep It SimpleWhile scoped slots are powerful, overusing them can lead to complex and hard-to-maintain code.
Document Your ComponentsWhen building reusable components, document the data provided through scoped slots so other developers can use them effectively.
Use Descriptive NamesName your scoped slot properties descriptively to avoid confusion.
By understanding how to access scoped slots in Vue 2, you can leverage this feature to create dynamic, reusable, and maintainable components. Scoped slots not only enhance the flexibility of your applications but also improve the overall development experience in Vue.js.
Explore scoped slots in your next Vue 2 project and discover how they can simplify your component structure while making your application more powerful.
0 notes
codehunger · 4 years ago
Text
How to pass value to child component in Vue.js
How to pass value to child component in Vue.js
Hello buddy, in this blog we will see how we can pass value to the child component in vue.js and we will also learn the use of props. Sharing data across components is one of the core functionalities of VueJS. It allows you to design a more modular project, control data scopes, and create a natural flow of data across your app. Think you are using the Vue tab component where you have put 5oo…
Tumblr media
View On WordPress
0 notes
holytheoristtastemaker · 5 years ago
Link
 Have you ever seen a calendar on a webpage and thought, how the heck did they did that? For something like that, it might be natural to reach for a plugin, or even an embedded Google Calendar, but it’s actually a lot more straightforward to make one than you might think. Especially when we use the component-driven power of Vue.
I’ve set up a demo over at CodeSandbox so you can see what we’re aiming for, but it’s always a good idea to spell out what we’re trying to do:
Create a month view grid that displays the days of the current month
Display dates from the previous and next months to so the grid is always full
Indicate the current date
Show the name of the currently selected month
Navigate to the previous and next month
Allow the user to navigate back to the current month with a single click
Oh, and we’ll build this as a single page application that fetches calendar dates from Day.js, a super light utility library.
Step 1: Start with the basic markup
We’re going to jump straight into templates. If you’re new to Vue, Sarah’s introduction series is a nice place to start. It’s also worth noting that I’ll be linking to the Vue 2 docs throughout this post. Vue 3 is currently in beta and the docs for it are subject to change.
Let’s start with creating a basic template for our calendar. We can outline our markup as three layers where we have:
A section for the calendar header. This will show components with the currently selected month and the elements responsible for paginating between months.
A section for the calendar grid header. A table header that holds a list containing the days of the week, starting with Monday.
The calendar grid. You know, each day in the current month, represented as a square in the grid.
Let’s write this up in a file called CalendarMonth.vue. This will be our main component.
<!-- CalendarMonth.vue --> <template>   <!-- Parent container for the calendar month -->   <div class="calendar-month">          <!-- The calendar header -->     <div class="calendar-month-header"       <!-- Month name -->       <CalendarDateIndicator />       <!-- Pagination -->       <CalendarDateSelector />     </div>     <!-- Calendar grid header -->     <CalendarWeekdays />     <!-- Calendar grid -->     <ol class="days-grid">       <CalendarMonthDayItem />     </ol>   </div> </template>
Now that we have some markup to work with, let’s go one step further and create required components.
Step 2: Header components
In our header we have two components:
CalendarDateIndicator shows the currently selected month.
CalendarDateSelector is responsible for paginating between months.
Let’s start with CalendarDateIndicator. This component will accept a selectedDate property which is a Day.js object that will format the current date properly and show it to the user.
<!-- CalendarDateIndicator.vue --> <template>   <div class="calendar-date-indicator"></div> </template> <script> export default {   props: {   selectedDate: {     type: Object,     required: true   } },   computed: {     selectedMonth() {       return this.selectedDate.format("MMMM YYYY");     }   } }; </script>
That was easy. Let’s go and create the pagination component that lets us navigate between months. It will contain three elements responsible for selecting the previous, current and next month. We’ll add an event listener on those that fires the appropriate method when the element is clicked.
<!-- CalendarDateSelector.vue --> <template>   <div class="calendar-date-selector">     <span @click="selectPrevious">﹤</span>     <span @click="selectCurrent">Today</span>     <span @click="selectNext">﹥</span>   </div> </template>
Then, in the script section, we will set up two props that the component will accept:
currentDate allows us to come back to current month when the “Today” button is clicked.
selectedDate tells us what month is currently selected.
We will also define methods responsible for calculating the new selected date based on the currently selected date using the subtract and add methods from Day.js. Each method will also $emit an event to the parent component with the newly selected month. This allows us to keep the value of selected date in one place — which will be our CalendarMonth.vue component — and pass it down to all child components (i.e. header, calendar grid).
// CalendarDateSelector.vue <script> import dayjs from "dayjs"; export default {   name: "CalendarDateSelector",   props: {     currentDate: {       type: String,       required: true     },     selectedDate: {       type: Object,       required: true     }   },   methods: {     selectPrevious() {       let newSelectedDate = dayjs(this.selectedDate).subtract(1, "month");       this.$emit("dateSelected", newSelectedDate);     },     selectCurrent() {       let newSelectedDate = dayjs(this.currentDate);       this.$emit("dateSelected", newSelectedDate);     },     selectNext() {       let newSelectedDate = dayjs(this.selectedDate).add(1, "month");       this.$emit("dateSelected", newSelectedDate);     }   } }; </script>
Now, let’s go back to the CalendarMonth.vue component and use our newly created components.
To use them we first need to import and register the components, also we need to create the values that will be passed as props to those components:
today properly formats today’s date and is used as a value for the “Today” pagination button.
selectedDate is the currently selected date (set to today’s date by default).
The last thing we need to do before we can render the components is create a method that’s responsible for changing the value of selectedDate. This method will be fired when the event from the pagination component is received.
// CalendarMonth.vue <script> import dayjs from "dayjs"; import CalendarDateIndicator from "./CalendarDateIndicator"; import CalendarDateSelector from "./CalendarDateSelector"; export default {   components: {     CalendarDateIndicator,     CalendarDateSelector   },   data() {     return {       selectedDate: dayjs(),       today: dayjs().format("YYYY-MM-DD")     };   },   methods: {     selectDate(newSelectedDate) {       this.selectedDate = newSelectedDate;     }   } }; </script>
Now we have everything we need to render our calendar header:
<!-- CalendarMonth.vue --> <template>   <div class="calendar-month">     <div class="calendar-month-header">       <CalendarDateIndicator         :selected-date="selectedDate"         class="calendar-month-header-selected-month"       />       <CalendarDateSelector         :current-date="today"         :selected-date="selectedDate"         @dateSelected="selectDate"       />     </div>   </div> </template>
This is a good spot to stop and see what we have so far. Our calendar header is doing everything we want, so let’s move forward and create components for our calendar grid.
Step 3: Calendar grid components
Here, again, we have two components:
CalendarWeekdays shows the names of the weekdays.
CalendarMonthDayItem represents a single day in the calendar.
The CalendarWeekdays component contains a list that iterates through the weekday labels (using the v-for directive) and renders that label for each weekday. In the script section, we need to define our weekdays and create a computed property to make it available in the template and cache the result to prevent us from having to re-calculate it in the future.
// CalendarWeekdays.vue <template>   <ol class="day-of-week">     <li v-for="weekday in weekdays" :key="weekday" > </li>   </ol> </template> 
 <script> const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; export default {   name: 'CalendarWeekdays',   computed: {     weekdays() {       return WEEKDAYS     }   } } </script>
Next is CalendarMonthDayItem. It’s a list item that receives a day property that is an object, and a boolean prop, isToday, that allows us to style the list item to indicate that it’s the current date. We also have one computed property that formats the received day object to our desired date format (D, or the numeric day of the month).
// CalendarMonthDayItem.vue <template>   <li     class="calendar-day"     :class="{       'calendar-day--not-current': !isCurrentMonth,       'calendar-day--today': isToday     }"   >     <span></span>   </li> </template> 
 <script> import dayjs from "dayjs"; export default {   name: "CalendarMonthDayItem",   props: {     day: {       type: Object,       required: true     },     isCurrentMonth: {       type: Boolean,       default: false     },     isToday: {       type: Boolean,       default: false     }   },   computed: {     label() {       return dayjs(this.day.date).format("D");     }   } }; </script>
OK, now that we have these two components, let’s see how we can add them to our CalendarMonth component.
We first need to import and register them. We also need to create a computedproperty that will return an array of objects representing our days. Each day contains a date property and isCurrentMonth property.
// CalendarMonth.vue <script> import dayjs from "dayjs"; import CalendarMonthDayItem from "./CalendarMonthDayItem"; import CalendarWeekdays from "./CalendarWeekdays"; 
 export default {   name: "CalendarMonth",   components: {     // ...     CalendarMonthDayItem,     CalendarWeekdays   },   computed: {     days() {       return [         { date: "2020-06-29", isCurrentMonth: false },         { date: "2020-06-30", isCurrentMonth: false },         { date: "2020-07-01", isCurrentMonth: true },         { date: "2020-07-02", isCurrentMonth: true },         // ...         { date: "2020-07-31", isCurrentMonth: true },         { date: "2020-08-01", isCurrentMonth: false },         { date: "2020-08-02", isCurrentMonth: false }       ];     }   } }; </script>
Then, in the template, we can render our components. Again, we use the v-fordirective to render the required number of day elements.
<!-- CalendarMonth.vue --> <template>   <div class="calendar-month">     <div class="calendar-month-header">       // ...     </div>     <CalendarWeekdays/>     <ol class="days-grid">       <CalendarMonthDayItem         v-for="day in days"         :key="day.date"         :day="day"         :is-today="day.date === today"       />     </ol>   </div> </template>
OK, things are starting to look good now. Have a look at where we are. It looks nice but, as you probably noticed, the template only contains static data at the moment. The month is hardcoded as July and the day numbers are hardcoded as well. We will change that by calculating what date should be shown on a specific month. Let’s dive into the code!
Step 4: Setting up current month calendar
Let’s think how we can calculate the date that should be shown on a specific month. That’s where Day.js really comes into play. It provides all the data we need to properly place dates on the correct days of the week for a given month using real calendar data. It allows us to get and set anything from the start date of a month to all the date formatting options we need to display the data.
We will:
Get the current month
Calculate where the days should be placed (weekdays)
Calculate the days for displaying dates from the previous and next months
Put all of the days together in a single array
We already have Day.js imported in our CalendarMonth component. We’re also going to lean on a couple of Day.js plugins for help. WeekDay helps us set the first day of the week. Some prefer Sunday as the first day of the week. Other prefer Monday. Heck, in some cases, it makes sense to start with Friday. We’re going to start with Monday.
The WeekOfYear plugin returns the numeric value for the current week out of all weeks in the year. There are 52 weeks in a year, so we’d say that the week starting January 1 is the the first week of the year, and so on.
Here’s what we put into CalendarMonth.vue to put all of that to use:
// CalendarMonth.vue <script> import dayjs from "dayjs"; import weekday from "dayjs/plugin/weekday"; import weekOfYear from "dayjs/plugin/weekOfYear"; // ... 
 dayjs.extend(weekday); dayjs.extend(weekOfYear); // ...
That was pretty straightforward but now the real fun starts as we will now play with the calendar grid. Let’s stop for a second a think what we really need to do to get that right.
First, we want the date numbers to fall in the correct weekday columns. For example, July 1, 2020, is on a Wednesday. That’s where the date numbering should start.
If the first of the month falls on Wednesday, then that means we’ll have empty grid items for Monday and Tuesday in the first week. The last day of the month is July 31, which falls on a Friday. That means Saturday and Sunday will be empty in the last week of the grid. We want to fill those with the trailing and leading dates of the previous and next months, respectively, so that the calendar grid is always full.
Tumblr media
Adding dates for the current month
To add the days of the current month to the grid, we need to know how many days exist in the current month. We can get that using the daysInMonth method provided by Day.js. Let’s create a computed property for that.
// CalendarMonth.vue computed: {   // ...   numberOfDaysInMonth() {       return dayjs(this.selectedDate).daysInMonth();   } }
When we know that, we create an empty array with a length that’s equal to number of days in the current month. Then we map() that array and create a day object for each one. The object we create has an arbitrary structure, so you can add other properties if you need them.
In this example, though, we need a date property that will be used to check if a particular date is the current day. We’ll also return a isCurrentMonth value that checks whether the date is in the current month or outside of it. If it is outside the current month, we will style those so folks know they are outside the range of the current month.
// CalendarMonth.vue computed: {   // ...   currentMonthDays() {     return [...Array(this.numberOfDaysInMonth)].map((day, index) => {       return {         date: dayjs(`${this.year}-${this.month}-${index + 1}`).format("YYYY-MM-DD")         isCurrentMonth: true       };     });   }, }
Adding dates from the previous month
To get dates from the previous month to display in the current month, we need to check what the weekday of the first day is in selected month. That’s where we can use the WeekDay plugin for Day.js. Let’s create a helper method for that.
// CalendarMonth.vue methods: {   // ...   getWeekday(date) {     return dayjs(date).weekday();   }, }
Then, based on that, we need to check which day was the last Monday in the previous month. We need that value to know how many days from the previous month should be visible in the current month view. We can get that by subtracting the weekday value from the first day of the current month. For example, if first day of the month is Wednesday, we need to subtract three days to get last Monday of the previous month. Having that value allows us to create an array of day objects starting from the last Monday of the previous month through the end of that month.
// CalendarMonth.vue computed: {   // ...   previousMonthDays() {     const firstDayOfTheMonthWeekday = this.getWeekday(this.currentMonthDays[0].date);     const previousMonth = dayjs(`${this.year}-${this.month}-01`).subtract(1, "month");     const previousMonthLastMondayDayOfMonth = dayjs(this.currentMonthDays[0].date).subtract(firstDayOfTheMonthWeekday - 1, "day").date();     // Cover first day of the month being sunday      (firstDayOfTheMonthWeekday === 0)     const visibleNumberOfDaysFromPreviousMonth = firstDayOfTheMonthWeekday ? firstDayOfTheMonthWeekday - 1 : 6;     return [...Array(visibleNumberOfDaysFromPreviousMonth)].map((day, index) = {       return {         date: dayjs(`${previousMonth.year()}-${previousMonth.month() + 1}-${previousMonthLastMondayDayOfMonth + index}`).format("YYYY-MM-DD"),         isCurrentMonth: false       };     });   } }
Adding dates from the next month
Now, let’s do the reverse and calculate which days we need from the next month to fill in the grid for the current month. Fortunately, we can use the same helper we just created for the previous month calculation. The difference is that we will calculate how many days from the next month should be visible by subtracting that weekday numeric value from seven.
So, for example, if the last day of the month is Saturday, we need to subtract one day from seven to construct an array of dates needed from next month (Sunday).
// CalendarMonth.vue computed: {   // ...   nextMonthDays() {     const lastDayOfTheMonthWeekday = this.getWeekday(`${this.year}-${this.month}-${this.currentMonthDays.length}`);     const nextMonth = dayjs(`${this.year}-${this.month}-01`).add(1, "month");     const visibleNumberOfDaysFromNextMonth = lastDayOfTheMonthWeekday ? 7 - lastDayOfTheMonthWeekday : lastDayOfTheMonthWeekday;     return [...Array(visibleNumberOfDaysFromNextMonth)].map((day, index) => {       return {         date: dayjs(`${nextMonth.year()}-${nextMonth.month() + 1}-${index + 1}`).format("YYYY-MM-DD"),         isCurrentMonth: false       };     });   } }
OK, we know how to create all days we need, so let’s use them and merge all days into a single array of all the days we want to show in the current month, including filler dates from the previous and next months.
// CalendarMonth.vue computed: {   // ...   days() {     return [       ...this.previousMonthDays,       ...this.currentMonthDays,       ...this.nextMonthDays     ];   }, }
0 notes
suzanneshannon · 5 years ago
Text
Let’s Make a Vue-Powered Monthly Calendar
Have you ever seen a calendar on a webpage and thought, how the heck did they did that? For something like that, it might be natural to reach for a plugin, or even an embedded Google Calendar, but it’s actually a lot more straightforward to make one than you might think. Especially when we use the component-driven power of Vue.
I’ve set up a demo over at CodeSandbox so you can see what we’re aiming for, but it’s always a good idea to spell out what we’re trying to do:
Create a month view grid that displays the days of the current month
Display dates from the previous and next months to so the grid is always full
Indicate the current date
Show the name of the currently selected month
Navigate to the previous and next month
Allow the user to navigate back to the current month with a single click
Oh, and we’ll build this as a single page application that fetches calendar dates from Day.js, a super light utility library.
Step 1: Start with the basic markup
We’re going to jump straight into templates. If you’re new to Vue, Sarah’s introduction series is a nice place to start. It’s also worth noting that I’ll be linking to the Vue 2 docs throughout this post. Vue 3 is currently in beta and the docs for it are subject to change.
Let’s start with creating a basic template for our calendar. We can outline our markup as three layers where we have:
A section for the calendar header. This will show components with the currently selected month and the elements responsible for paginating between months.
A section for the calendar grid header. A table header that holds a list containing the days of the week, starting with Monday.
The calendar grid. You know, each day in the current month, represented as a square in the grid.
Let’s write this up in a file called CalendarMonth.vue. This will be our main component.
<!-- CalendarMonth.vue --> <template>   <!-- Parent container for the calendar month -->   <div class="calendar-month">          <!-- The calendar header -->     <div class="calendar-month-header"       <!-- Month name -->       <CalendarDateIndicator />       <!-- Pagination -->       <CalendarDateSelector />     </div>     <!-- Calendar grid header -->     <CalendarWeekdays />     <!-- Calendar grid -->     <ol class="days-grid">       <CalendarMonthDayItem />     </ol>   </div> </template>
Now that we have some markup to work with, let’s go one step further and create required components.
Step 2: Header components
In our header we have two components:
CalendarDateIndicator shows the currently selected month.
CalendarDateSelector is responsible for paginating between months.
Let’s start with CalendarDateIndicator. This component will accept a selectedDate property which is a Day.js object that will format the current date properly and show it to the user.
<!-- CalendarDateIndicator.vue --> <template>   <div class="calendar-date-indicator"></div> </template> <script> export default {   props: {   selectedDate: {     type: Object,     required: true   } },   computed: {     selectedMonth() {       return this.selectedDate.format("MMMM YYYY");     }   } }; </script>
That was easy. Let’s go and create the pagination component that lets us navigate between months. It will contain three elements responsible for selecting the previous, current and next month. We’ll add an event listener on those that fires the appropriate method when the element is clicked.
<!-- CalendarDateSelector.vue --> <template>   <div class="calendar-date-selector">     <span @click="selectPrevious">﹤</span>     <span @click="selectCurrent">Today</span>     <span @click="selectNext">﹥</span>   </div> </template>
Then, in the script section, we will set up two props that the component will accept:
currentDate allows us to come back to current month when the “Today” button is clicked.
selectedDate tells us what month is currently selected.
We will also define methods responsible for calculating the new selected date based on the currently selected date using the subtract and add methods from Day.js. Each method will also $emit an event to the parent component with the newly selected month. This allows us to keep the value of selected date in one place — which will be our CalendarMonth.vue component — and pass it down to all child components (i.e. header, calendar grid).
// CalendarDateSelector.vue <script> import dayjs from "dayjs"; export default {   name: "CalendarDateSelector",   props: {     currentDate: {       type: String,       required: true     },     selectedDate: {       type: Object,       required: true     }   },   methods: {     selectPrevious() {       let newSelectedDate = dayjs(this.selectedDate).subtract(1, "month");       this.$emit("dateSelected", newSelectedDate);     },     selectCurrent() {       let newSelectedDate = dayjs(this.currentDate);       this.$emit("dateSelected", newSelectedDate);     },     selectNext() {       let newSelectedDate = dayjs(this.selectedDate).add(1, "month");       this.$emit("dateSelected", newSelectedDate);     }   } }; </script>
Now, let’s go back to the CalendarMonth.vue component and use our newly created components.
To use them we first need to import and register the components, also we need to create the values that will be passed as props to those components:
today properly formats today’s date and is used as a value for the “Today” pagination button.
selectedDate is the  currently selected date (set to today’s date by default).
The last thing we need to do before we can render the components is create a method that’s responsible for changing the value of selectedDate. This method will be fired when the event from the pagination component is received.
// CalendarMonth.vue <script> import dayjs from "dayjs"; import CalendarDateIndicator from "./CalendarDateIndicator"; import CalendarDateSelector from "./CalendarDateSelector"; export default {   components: {     CalendarDateIndicator,     CalendarDateSelector   },   data() {     return {       selectedDate: dayjs(),       today: dayjs().format("YYYY-MM-DD")     };   },   methods: {     selectDate(newSelectedDate) {       this.selectedDate = newSelectedDate;     }   } }; </script>
Now we have everything we need to render our calendar header:
<!-- CalendarMonth.vue --> <template>   <div class="calendar-month">     <div class="calendar-month-header">       <CalendarDateIndicator         :selected-date="selectedDate"         class="calendar-month-header-selected-month"       />       <CalendarDateSelector         :current-date="today"         :selected-date="selectedDate"         @dateSelected="selectDate"       />     </div>   </div> </template>
This is a good spot to stop and see what we have so far. Our calendar header is doing everything we want, so let’s move forward and create components for our calendar grid.
Step 3: Calendar grid components
Here, again, we have two components:
CalendarWeekdays shows the names of the weekdays.
CalendarMonthDayItem represents a single day in the calendar.
The CalendarWeekdays component contains a list that iterates through the weekday labels (using the v-for directive) and renders that label for each weekday. In the script section, we need to define our weekdays and create a computed property to make it available in the template and cache the result to prevent us from having to re-calculate it in the future.
// CalendarWeekdays.vue <template>   <ol class="day-of-week">     <li v-for="weekday in weekdays" :key="weekday" > </li>   </ol> </template> 
 <script> const WEEKDAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]; export default {   name: 'CalendarWeekdays',   computed: {     weekdays() {       return WEEKDAYS     }   } } </script>
Next is CalendarMonthDayItem. It’s a list item that receives a day property that is an object, and a boolean prop, isToday, that allows us to style the list item to indicate that it’s the current date. We also have one computed property that formats the received day object to our desired date format (D, or the numeric day of the month).
// CalendarMonthDayItem.vue <template>   <li     class="calendar-day"     :class="{       'calendar-day--not-current': !isCurrentMonth,       'calendar-day--today': isToday     }"   >     <span></span>   </li> </template> 
 <script> import dayjs from "dayjs"; export default {   name: "CalendarMonthDayItem",   props: {     day: {       type: Object,       required: true     },     isCurrentMonth: {       type: Boolean,       default: false     },     isToday: {       type: Boolean,       default: false     }   },   computed: {     label() {       return dayjs(this.day.date).format("D");     }   } }; </script>
OK, now that we have these two components, let’s see how we can add them to our CalendarMonth component.
We first need to import and register them. We also need to create a computed property that will return an array of objects representing our days. Each day contains a date property and isCurrentMonth property.
// CalendarMonth.vue <script> import dayjs from "dayjs"; import CalendarMonthDayItem from "./CalendarMonthDayItem"; import CalendarWeekdays from "./CalendarWeekdays"; 
 export default {   name: "CalendarMonth",   components: {     // ...     CalendarMonthDayItem,     CalendarWeekdays   },   computed: {     days() {       return [         { date: "2020-06-29", isCurrentMonth: false },         { date: "2020-06-30", isCurrentMonth: false },         { date: "2020-07-01", isCurrentMonth: true },         { date: "2020-07-02", isCurrentMonth: true },         // ...         { date: "2020-07-31", isCurrentMonth: true },         { date: "2020-08-01", isCurrentMonth: false },         { date: "2020-08-02", isCurrentMonth: false }       ];     }   } }; </script>
Then, in the template, we can render our components. Again, we use the v-for directive to render the required number of day elements.
<!-- CalendarMonth.vue --> <template>   <div class="calendar-month">     <div class="calendar-month-header">       // ...     </div>     <CalendarWeekdays/>     <ol class="days-grid">       <CalendarMonthDayItem         v-for="day in days"         :key="day.date"         :day="day"         :is-today="day.date === today"       />     </ol>   </div> </template>
OK, things are starting to look good now. Have a look at where we are. It looks nice but, as you probably noticed, the template only contains static data at the moment. The month is hardcoded as July and the day numbers are hardcoded as well. We will change that by calculating what date should be shown on a specific month. Let’s dive into the code!
Step 4: Setting up current month calendar
Let’s think how we can calculate the date that should be shown on a specific month. That’s where Day.js really comes into play. It provides all the data we need to properly place dates on the correct days of the week for a given month using real calendar data. It allows us to get and set anything from the start date of a month to all the date formatting options we need to display the data.
We will:
Get the current month
Calculate where the days should be placed (weekdays)
Calculate the days for displaying dates from the previous and next months
Put all of the days together in a single array
We already have Day.js imported in our CalendarMonth component. We’re also going to lean on a couple of Day.js plugins for help. WeekDay helps us set the first day of the week. Some prefer Sunday as the first day of the week. Other prefer Monday. Heck, in some cases, it makes sense to start with Friday. We’re going to start with Monday.
The WeekOfYear plugin returns the numeric value for the current week out of all weeks in the year. There are 52 weeks in a year, so we’d say that the week starting January 1 is the the first week of the year, and so on.
Here’s what we put into CalendarMonth.vue to put all of that to use:
// CalendarMonth.vue <script> import dayjs from "dayjs"; import weekday from "dayjs/plugin/weekday"; import weekOfYear from "dayjs/plugin/weekOfYear"; // ... 
 dayjs.extend(weekday); dayjs.extend(weekOfYear); // ...
That was pretty straightforward but now the real fun starts as we will now play with the calendar grid. Let’s stop for a second a think what we really need to do to get that right.
First, we want the date numbers to fall in the correct weekday columns. For example, July 1, 2020, is on a Wednesday. That’s where the date numbering should start.
If the first of the month falls on Wednesday, then that means we’ll have empty grid items for Monday and Tuesday in the first week. The last day of the month is July 31, which falls on a Friday. That means Saturday and Sunday will be empty in the last week of the grid. We want to fill those with the trailing and leading dates of the previous and next months, respectively, so that the calendar grid is always full.
Tumblr media
Adding dates for the current month
To add the days of the current month to the grid, we need to know how many days exist in the current month. We can get that using the daysInMonth method provided by Day.js. Let’s create a computed property for that.
// CalendarMonth.vue computed: {   // ...   numberOfDaysInMonth() {       return dayjs(this.selectedDate).daysInMonth();   } }
When we know that, we create an empty array with a length that’s equal to number of days in the current month. Then we map() that array and create a day object for each one. The object we create has an arbitrary structure, so you can add other properties if you need them.
In this example, though, we need a date property that will be used to check if a particular date is the current day. We’ll also return a isCurrentMonth value that checks whether the date is in the current month or outside of it. If it is outside the current month, we will style those so folks know they are outside the range of the current month.
// CalendarMonth.vue computed: {   // ...   currentMonthDays() {     return [...Array(this.numberOfDaysInMonth)].map((day, index) => {       return {         date: dayjs(`${this.year}-${this.month}-${index + 1}`).format("YYYY-MM-DD")         isCurrentMonth: true       };     });   }, }
Adding dates from the previous month
To get dates from the previous month to display in the current month, we need to check what the weekday of the first day is in selected month. That’s where we can use the WeekDay plugin for Day.js. Let’s create a helper method for that.
// CalendarMonth.vue methods: {   // ...   getWeekday(date) {     return dayjs(date).weekday();   }, }
Then, based on that, we need to check which day was the last Monday in the previous month. We need that value to know how many days from the previous month should be visible in the current month view. We can get that by subtracting the weekday value from the first day of the current month. For example, if first day of the month is Wednesday, we need to subtract three days to get last Monday of the previous month. Having that value allows us to create an array of day objects starting from the last Monday of the previous month through the end of that month.
// CalendarMonth.vue computed: {   // ...   previousMonthDays() {     const firstDayOfTheMonthWeekday = this.getWeekday(this.currentMonthDays[0].date);     const previousMonth = dayjs(`${this.year}-${this.month}-01`).subtract(1, "month");     const previousMonthLastMondayDayOfMonth = dayjs(this.currentMonthDays[0].date).subtract(firstDayOfTheMonthWeekday - 1, "day").date();     // Cover first day of the month being sunday      (firstDayOfTheMonthWeekday === 0)     const visibleNumberOfDaysFromPreviousMonth = firstDayOfTheMonthWeekday ? firstDayOfTheMonthWeekday - 1 : 6;     return [...Array(visibleNumberOfDaysFromPreviousMonth)].map((day, index) = {       return {         date: dayjs(`${previousMonth.year()}-${previousMonth.month() + 1}-${previousMonthLastMondayDayOfMonth + index}`).format("YYYY-MM-DD"),         isCurrentMonth: false       };     });   } }
Adding dates from the next month
Now, let’s do the reverse and calculate which days we need from the next month to fill in the grid for the current month. Fortunately, we can use the same helper we just created for the previous month calculation. The difference is that we will calculate how many days from the next month should be visible by subtracting that weekday numeric value from seven.
So, for example, if the last day of the month is Saturday, we need to subtract one day from seven to construct an array of dates needed from next month (Sunday).
// CalendarMonth.vue computed: {   // ...   nextMonthDays() {     const lastDayOfTheMonthWeekday = this.getWeekday(`${this.year}-${this.month}-${this.currentMonthDays.length}`);     const nextMonth = dayjs(`${this.year}-${this.month}-01`).add(1, "month");     const visibleNumberOfDaysFromNextMonth = lastDayOfTheMonthWeekday ? 7 - lastDayOfTheMonthWeekday : lastDayOfTheMonthWeekday;     return [...Array(visibleNumberOfDaysFromNextMonth)].map((day, index) => {       return {         date: dayjs(`${nextMonth.year()}-${nextMonth.month() + 1}-${index + 1}`).format("YYYY-MM-DD"),         isCurrentMonth: false       };     });   } }
OK, we know how to create all days we need, so let’s use them and merge all days into a single array of all the days we want to show in the current month, including filler dates from the previous and next months.
// CalendarMonth.vue computed: {   // ...   days() {     return [       ...this.previousMonthDays,       ...this.currentMonthDays,       ...this.nextMonthDays     ];   }, }
 Voilà, there we have it! Check out the final demo to see everything put together.
The post Let’s Make a Vue-Powered Monthly Calendar appeared first on CSS-Tricks.
You can support CSS-Tricks by being an MVP Supporter.
Let’s Make a Vue-Powered Monthly Calendar published first on https://deskbysnafu.tumblr.com/
0 notes
motherfucking-russia · 5 years ago
Text
Watch Directv
AT&T‘s Internet-streaming live TV service will soon be specific to the Chrome browser, assuming you favour to circulation for your computer or computing device. Users are reporting seeing a message when trying to move on PC that advises them to download and install Google Chrome, pronouncing its miles vital with the intention to get the ‘best streaming revel in.’ You have till the give up of this month to make the transition.
If you subscribe to DirecTV NOW and also you log into your account on a PC's browser, you’ll be greeted with a message that asserts, in component, ‘DirecTV NOW will stay solely on Google Chrome while accessed through your laptop.’ The word goes on to give an explanation for that the provider will drop its support for Internet Explorer and Safari ‘after June.’
Tumblr media
This trade simplest impacts folks that try and watch the carrier from a computing device browser; the service is viewable thru a devoted app while watching from a cellphone or pill. Presumably, as soon as the aid is dropped, folks that try and get admission to the provider the usage of Explorer or Safari could be directed to download Chrome before getting access to the video content material.
The organization has no longer revealed why it's far making this modification — except to say that Chrome will in a few ways offer the excellent viewing enjoy — and it hasn’t but updated any of its assist pages to indicate the upcoming change, which is a chunk ordinary. Regardless, you've got approximately 3 weeks left to make the transition…either to Chrome or to an extraordinary OTT video carrier. Competing products consist of PlayStation Vue, Sling TV, and Hulu Live TV.
WHAT IS DIRECTV APP FOR PC
Directv is a premium subscription-based satellite tv carrier issuer which becomes began in 1994.  The company has been successfully completed its 23 years. At Directv, you could subscribe tv and audio offerings.  It makes use of satellite transmission to offer their offerings to their customers. Its audio and tv services are confined to the United States, Latin America, and the Caribbean. It doesn’t provide their offerings international.
OTHER PRODUCTS OFFERED BY DIRECTV
Direct broadcast satellite tv for pc
Pay Television
Pay-in line with-view
Internet Television
Owner    AT&T
Read Kinemaster for PC
SUBSCRIPTION OFFERED BY THE DIRECTV
Local tv stations
broadcast television networks
Subscription-based total tv offerings
Satellite radio services
private video services
HOW TO WATCH DIRECTV ON PC
If you're one that loves looking movies and TV suggests so that you must strive the Directv which help you get right of entry to movies and indicates anytime & anywhere if you have a working internet connection.
Below we're sharing how you may start taking part in the content of Directv on a Home windows PC (Computer)
Visit here DIRECTV entertainment website
Log in along with your subscription keys
Now faucet “watch online”
It will carry you the listing of films, simply select one
Enjoy
Features of Directv APK
Watch Favorite shows and films
It gives its customers the element to watch their boundless fav serials and films which customers can see Live or On-Demand. Another extra element is to get the Data Free TV which allows viewing DIRECTV on the gadgets, without utilising the patron’s net facts. Besides, customers should purchase into the top-notch channels which permit viewing the maximum latest content.
Recording
Directv gives a highlight of recording the fav serials and movies from anyplace in order that viewers don’t pass over out on their favourite content material and can view it every time as consistent with their requirements.
Read MainStage 3 for PC Download Free
Total Control
This component permits its customers to use their devices to pause, play, and rewind the serials and films which can be streaming on their TV. At the point when somebody wishes to search for a show, the subscriber can actually communicate out and voice seek highlight can help discover exactly what clients are trying to find. At that point, they can even arrange it to reveal consequences on the TeleVision. Most importantly, Users can set parental controls and respect large serenity over what their children are viewing.
Easy Interface
It is having an exceedingly easy to make use of interface which makes your work excessively truthful. The on-hand channels incorporate every one of the channels immediately from the child’s quarter to adults.
More info Clicks Helpsforpc.com
0 notes
laravelvuejs · 5 years ago
Photo
Tumblr media
Vue JS 2 Tutorial #24 – Events (child to parent) Hey gang, in this Vue JS tutorial I'll introduce you to events, and how we can use them to pass data from a child component to a parent component in reaction to ... source
0 notes
t-baba · 6 years ago
Photo
Tumblr media
A Beginner’s Guide to Working With Components in Vue
One of the great things about working with Vue is its component-based approach to building user interfaces. This allows you to break your application into smaller, reusable pieces (components) which you can then use to build out a more complicated structure.
In this guide, I’ll offer you a high-level introduction to working with components in Vue. I’ll look at how to create components, how to pass data between components (via both props and an event bus) and how to use Vue’s <slot> element to render additional content within a component.
Each example will be accompanied by a runnable CodePen demo.
How to Create Components in Vue
Components are essentially reusable Vue instances with a name. There are various ways to create components within a Vue application. For example, in a small- to medium-sized project you can use the Vue.component method to register a global component, like so:
Vue.component('my-counter', { data() { return { count: 0 } }, template: `<div></div>` }) new Vue({ el: '#app' })
The name of the component is my-counter. It can be used like so:
<div id="app"> <my-counter></my-counter> </div>
When naming your component, you can choose kebab case (my-custom-component) or Pascal case (MyCustomComponent). You can use either variation when referencing your component from within a template, but when referencing it directly in the DOM (as in the example above), only the kebab case tag name is valid.
You might also notice that, in the example above, data is a function which returns an object literal (as opposed to being an object literal itself). This is so that each instance of the component receives its own data object and doesn’t have to share one global instance with all other instances.
There are several ways to define a component template. Above we are using a template literal, but we could also use a <script tag> marked with text/x-template or an in-DOM template. You can read more about the different ways of defining templates here.
Single-file Components
In more complex projects, global components can quickly become unwieldy. In such cases, it makes sense to craft your application to use single-file components. As the name suggests, these are single files with a .vue extension, which contain a <template>, <script> and <style> section.
For our example above, an App component might look like this:
<template> <div id="app"> <my-counter></my-counter> </div> </template> <script> import myCounter from './components/myCounter.vue' export default { name: 'app', components: { myCounter } } </script> <style></style>
And a MyCounter component might look like this:
<template> <div></div> </template> <script> export default { name: 'my-counter', data() { return { count: 0 } } } </script> <style></style>
As you can see, when using single-file components, it’s possible to import and use these directly within the components where they’re needed.
In this guide, I’ll present all of the examples using the Vue.component() method of registering a component.
Using single-file components generally involves a build step (for example, with Vue CLI). If this is something you’d like to find out more about, please check out “A Beginner’s Guide to Vue CLI” in this Vue series.
Passing Data to Components Via Props
Props enable us to pass data from a parent component to child component. This makes it possible for our components to be in smaller chunks to handle specific functionalities. For example, if we have a blog component we might want to display information such as the author’s details, post details (title, body and images) and comments.
We can break these into child components, so that each component handles specific data, making the component tree look like this:
<BlogPost> <AuthorDetails></AuthorDetails> <PostDetails></PostDetails> <Comments></Comments> </BlogPost>
If you’re still not convinced about the benefits of using components, take a moment to realize how useful this kind of composition can be. If you were to revisit this code in the future, it would be immediately obvious how the page is structured and where (that is, in which component) you should look for which functionality. This declarative way of composing an interface also makes it much easier for someone who isn’t familiar with a codebase to dive in and become productive quickly.
Since all the data will be passed from the parent component, it can look like this:
new Vue({ el: '#app', data() { return { author: { name: 'John Doe', email: '[email protected]' } } } })
In the above component, we have the author details and post information defined. Next, we have to create the child component. Let’s call the child component author-detail. So our HTML template will look like this:
<div id="app"> <author-detail :owner="author"></author-detail> </div>
We’re passing the child component the author object as props with the name owner. It’s important to note the difference here. In the child component, owner is the name of the prop with which we receive the data from the parent component. The data we want to receive is called author, which we’ve defined in our parent component.
To have access to this data, we need to declare the props in the author-detail component:
Vue.component('author-detail', { template: ` <div> <h2></h2> <p></p> </div> ´, props: ['owner'] })
We can also enable validation when passing props, to make sure the right data is being passed. This is similar to PropTypes in React. To enable validation in the above example, change our component to look like this:
Vue.component('author-detail', { template: ` <div> <h2></h2> <p></p> </div> `, props: { owner: { type: Object, required: true } } })
If we pass the wrong prop type, you’ll see an error in your console that looks like what I have below:
"[Vue warn]: Invalid prop: type check failed for prop 'text'. Expected Boolean, got String. (found in component <>)"
There’s an official guide in the Vue docs that you can use to learn about prop validation.
See the Pen Vue Componets - Props by SitePoint (@SitePoint) on CodePen.
The post A Beginner’s Guide to Working With Components in Vue appeared first on SitePoint.
by Kingsley Silas via SitePoint https://ift.tt/2XrymCO
0 notes
codehunger · 4 years ago
Text
Vue-Emit data from child to parent in vue js
Vue-Emit data from child to parent in vue js
In this article, we will learn about how to emit data from child to parent in VueJS with the example, I will show you an example that how we can pass child data to our parent component, We will use emit method to pass the data from the child component to the parent component in vuejs. Let’s suppose my child component name as Child.vue and have the below code into it. <template> <div> <b-tabs…
Tumblr media
View On WordPress
1 note · View note
mbaljeetsingh · 8 years ago
Text
Intro to Vue.js: Components, Props, and Slots
This is the second part in a five-part series about the JavaScript framework, Vue.js. In this part, we'll go over Components, Props, and Slots. This is not intended to be a complete guide, but rather an overview of the basics to get you up and running so you can get to know Vue.js and understand what the framework has to offer.
Article Series:
Rendering, Directives, and Events
Components, Props, and Slots (You are here!)
Vue-cli (Coming soon!)
Vuex (Coming soon!)
Animations (Coming soon!)
Components and Passing Data
If you're familiar with React or Angular2, the idea of components and passing state won't be new to you. In case you're not, let's go through some of the main concepts.
Websites large and small are usually composed of different pieces, and abstracting them into smaller pieces makes them easy to structure, reason about, reuse, and makes our code more legible. Instead of digging through all of the markup in long, multi-faceted page, we could comprise it of components like this:
<header></header> <aside> <sidebar-item v-for="item in items"></sidebar-item> </aside> <main> <blogpost v-for="post in posts"></blogpost> </main> <footer></footer>
This is a simplified example, but you can see how useful this type of composition can be as you start to build out the structure of your site. If you were to dive into this code as a maintainer, it wouldn’t take much to understand how the application is structured or where to look for each piece.
Vue lets us create components in a few different ways. Let’s work from simple to complex, keeping in mind that the complex example is truest to form for what an average Vue application would look like.
app.$mount('#app'); var app = new Vue({ el: 'hello', template: '<h1>Hello World!</h1>' });
This works, but isn’t terribly useful as it can only be used once and we’re not yet passing the information to different components. One way to pass data from a parent to a child is called props.
This is as simple an example as I could make, so that it's super clear. Remember that the :text in the HTML is a shortcut for Vue binding. We covered this last time in the section on directives. Binding can be used for all kinds of things but in this instance, it keeps us from having to place the state in a mustache template, like this .
In the code below, Vue.component is the component, and new Vue is called the instance. You can have more than one instance in an applicatio. Typically, we'll have one instance and several components, as the instance is the main app.
Vue.component('child', { props: ['text'], template: `<div><div>` }); new Vue({ el: "#app", data() { return { message: 'hello mr. magoo' } } });
<div id="app"> <child :text="message"></child> </div>
See the Pen.
Now we can reuse this component as many times as we like through our application:
<div id="app"> <child :text="message"></child> <child :text="message"></child> </div>
See the Pen.
We can also add validation to our props, which is similar to PropTypes in React. This is nice because it's self-documenting, and will return an error if it's not what we expected, but only in development mode:
Vue.component('child', { props: { text: { type: String, required: true } }, template: `<div><div>` });
In the example below, I'm loading Vue in development mode, and purposefully passing an invalid type into our prop validation. You can see the error in the console. (It also helpful lets you know you can use Vue's devtools and where to find them).
Vue.component('child', { props: { text: { type: Boolean, required: true } }, template: `<div><div>` });
See the Pen simple props with validation by Sarah Drasner (@sdras) on CodePen.
Objects should be returned as a factory function and you can even pass as a custom validator function, which is really nice because you can check values against business, input, or other logic. There's a nice write-up of how you'd use each type in the guide here.
You don't need to necessarily pass the data in props to the child, either, you have the option of using state or a static value as you see fit:
Vue.component('child', { props: { count: { type: Number, required: true } }, template: `<div class="num"></div>` }) new Vue({ el: '#app', data() { return { count: 0 } }, methods: { increment() { this.count++; }, decrement() { this.count--; } } })
<div id="app"> <h3> <button @click="increment">+</button> Adjust the state <button @click="decrement">-</button> </h3> <h2>This is the app state: <span class="num"></span></h2> <hr> <h4><child count="1"></child></h4> <p>This is a child counter that is using a static integer as props</p> <hr> <h4><child :count="count"></child></h4> <p>This is the same child counter and it is using the state as props</p> </div>
See the Pen child component using and not using props by Sarah Drasner (@sdras) on CodePen.
The difference is whether or not you’re passing a property and binding it:
Not using the state <child count="1"></child>
vs
Using the state <child :count="count"></child>
Up until now, we've been creating content in our child component with a string, and of course if you’re using babel so that you can process ES6 in all browsers (which I highly suggest), you could use a template literal to avoid potentially hard-to-read string concatenation:
Vue.component('individual-comment', { template: `<li> </li>`, props: ['commentpost'] }); new Vue({ el: '#app', data: { newComment: '', comments: [ 'Looks great Julianne!', 'I love the sea', 'Where are you at?' ] }, methods: { addComment: function () { this.comments.push(this.newComment) this.newComment = '' } } });
<ul> <li is="individual-comment" v-for="comment in comments" v-bind:commentpost="comment" ></li> </ul> <input v-model="newComment" v-on:keyup.enter="addComment" placeholder="Add a comment" >
See the Pen cd81de1463229a9612dca7559dd666e0 by Sarah Drasner (@sdras) on CodePen.
This is a little more useful, but there's still a limit to how much content we probably want to put in that string, even with the help of template literals. Eventually in this comment form we'd want to have photos and the names of the authors, and you can already probably guess how crowded it would get with all that information. We also won't have any useful syntax highlighting within that string.
With all those things in mind, let’s create a template. We'll wrap some regular HTML in special script tags and use an id to reference it to create a component. You can see that this is a lot more legible when we have a lot of text and elements:
<!-- This is the Individual Comment Component --> <script type="text/x-template" id="comment-template"> <li> <img class="post-img" :src="commentpost.authorImg" /> <small></small> <p class="post-comment">""</p> </li> </script>
Vue.component('individual-comment', { template: '#comment-template', props: ['commentpost'] });
See the Pen Photo App post with Vue.js by Sarah Drasner (@sdras) on CodePen.
Slots
This is a lot better. But what happens when we have two components with slight variations, either content or style deviations? We could pass all the different content and styles down into the component with props, and switch everything out each time, or we could fork the components themselves and create different versions of them. But it would be really nice if we could reuse the components, and populate them with the same data or functionality. This is where slots come in really handy.
Let's say we have a main app instance using the same <app-child> component twice. Inside each child we want some of the same content, and some different content. For the content we want to stay consistent, we would use a standard p tag, and for the content we want to switch out, we'll put an empty <slot></slot> tag.
<script type="text/x-template" id="childarea"> <div class="child"> <slot></slot> <p>It's a veritable slot machine!<br> Ha ha aw</p> </div> </script>
Then, in the app instance, we can pass content inside the <app-child> component tags and it will automatically fill up the slots:
<div id="app"> <h2>We can use slots to populate content</h2> <app-child> <h3>This is slot number one</h3> </app-child> <app-child> <h3>This is slot number two</h3> <small>I can put more info in, too!</small> </app-child> </div>
See the Pen.
Alternatively, we can have particular styles assigned for different components, and keep all of the content inside the same, therefore quickly and easily changing out the appearance of something. In the wine label maker below, one of the buttons will toggle the component and color based on what the user selects, and the background of the bottle and label and text will all switch, while keeping the content within stable.
const app = new Vue({ ... components: { 'appBlack': { template: '#black' } } });
Main Vue App HTML:
<component :is="selected"> ... <path class="label" d="M12,295.9s56.5,5,137.6,0V409S78.1,423.6,12,409Z" transform="translate(-12 -13.8)" :style="{ fill: labelColor }"/> ... </component> <h4>Color</h4> <button @click="selected ='appBlack', labelColor = '#000000'">Black Label</button> <button @click="selected ='appWhite', labelColor = '#ffffff'">White Label</button> <input type="color" v-model="labelColor" defaultValue="#ff0000">
White Component HTML:
<script type="text/x-template" id="white"> <div class="white"> <slot></slot> </div> </script>
(This is a larger demo, so it might make more sense if you play with it in a separate window/tab)
See the Pen.
Now, we're putting all of the SVG image data in the main app, but it's actually placed inside the <slot> in each component. This allows us to switch out pieces of content, or style things differently based on the usage, which is a really nice feature. You can see that we've allowed the user to decide which component they'll be using by creating a button that changes the "selected" value of the component.
Right now we have everything in one slot but we could also use multiple slots, and differentiate them through naming if we'd like:
<!-- main vue app instance --> <app-comment> <p slot="comment"></p> </app-comment> <!-- individual component --> <script type="text/x-template" id="comment-template"> <div> <slot name="comment"></slot> </div> </script>
We can switch between different components with the same referenced slots easily, but what happens when we want to be able to switch back and forth, but hold on to the individual state of each component? Currently, when we switch between black and white the templates switch out and the content stays the same. But maybe we have a situation where we want the black label to be completely different than the white label. There's a special component you can wrap it in called <keep-alive></keep-alive> that will retain the state as you switch.
Check out this deviation of the example above- create a black label, and then a different white label, and switch between them. You will see that the state of each is preserved, and are different from one another:
<keep-alive> <component :is="selected"> ... </component> </keep-alive>
See the Pen Vue Wine Label Maker- with keep-alive by Sarah Drasner (@sdras) on CodePen.
I love this feature of the API.
This is all nice, but for simplicity’s sake, we've been sticking everything in one or two files. It would be much better organized while we build out our site if we could separate the components out into different files, and import them as we need them, and truly that's how real development in Vue is typically done, so let's run through that next. Tune in for the next part when we talk about Vue-cli, build processes, and Vuex for state management!
Article Series:
Rendering, Directives, and Events
Components, Props, and Slots (You are here!)
Vue-cli (Coming soon!)
Vuex (Coming soon!)
Animations (Coming soon!)
Intro to Vue.js: Components, Props, and Slots is a post from CSS-Tricks
via CSS-Tricks http://ift.tt/2kmKnVd
0 notes
laravelvuejs · 6 years ago
Text
Vue.js Tutorial From Scratch - e08 - Custom Events Passing Data from Child to Parent Component - VueJs
Vue.js Tutorial From Scratch – e08 – Custom Events Passing Data from Child to Parent Component – VueJs
Vue.js Tutorial From Scratch – e08 – Custom Events Passing Data from Child to Parent Component – VueJs
[ad_1]
Now that we have a nice modern npm and webpack build, let’s tackle getting our components to communicate. In Vue, this is done using custom events. We can emit an event on our child component and then listen for that event on our parent event. Follow along as we code a simple example from…
View On WordPress
0 notes
siliconwebx · 7 years ago
Text
Using Event Bus to Share Props Between Vue Components
By default, communication between Vue components happen with the use of props. Props are properties that are passed from a parent component to a child component. For example, here’s a component where title is a prop:
<blog-post title="My journey with Vue"></blog-post>
Props are always passed from the parent component to the child component. As your application increases in complexity, you slowly hit what is called prop drilling here’s a relate article that is React-focused, but totally applies). Prop drilling is the idea of passing props down and down and down to child components — and, as you might imagine, it’s generally a tedious process.
So, tedious prop drilling can be one potential problem in a complex. The other has to do with the communication between unrelated components. We can tackle all of this by making use of an Event Bus.
What is an Event Bus? Well, it’s kind of summed up in the name itself. It’s a mode of transportation for one component to pass props from one component to another, no matter where those components are located in the tree.
Practice task: Building a counter
Let’s build something together to demonstrate the concept of an event bus. A counter that adds or subtracts a submitted value and tallies the overall total is a good place to start:
See the Pen Vuejs Event Bus Counter by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.
To make use of an event bus, we first need to initialize it like so:
import Vue from 'vue'; const eventBus = new Vue();
This sets an instance of Vue to eventBus. You can name it anything you’d like, whatsoever. If you are making use of a single-file component, then you should have snippet in a separate file, since you will have to export the Vue instance assigned to eventBus anyway:
import Vue from 'vue'; export const eventBus = new Vue();
With that done, we can start making use of it in our counter component.
Here’s what we want to do:
We want to have a count with an initial value of 0.
We want an input field that accepts numeric values.
We want two buttons: one that will add the submitted numeric value to the count when clicked and the other to subtract that submitted numeric value from the count when clicked.
We want a confirmation of what happened when the count changes.
This is how the template looks with each of those elements in place:
<div id="app"> <h2>Counter</h2> <h2></h2> <input type="number" v-model="entry" /> <div class="div__buttons"> <button class="incrementButton" @click.prevent="handleIncrement"> Increment </button> <button class="decrementButton" @click.prevent="handleDecrement"> Decrement </button> </div> <p></p> </div>
We bind the input field to a value called entry, which we’ll use to either increase or decrease the count, depending on what is entered by the user. When either button is clicked, we trigger a method that should either increase or decrease the value of count. Finally, that thing contained in <p> tag is the message we’ll print that summarizes the change to the count.
Here’s how that all comes together in our script:
new Vue({ el: '#app', data() { return { count: 0, text: '', entry: 0 } }, created() { eventBus.$on('count-incremented', () => { this.text = `Count was increased` setTimeout(() => { this.text = ''; }, 3000); }) eventBus.$on('count-decremented', () => { this.text = `Count was decreased` setTimeout(() => { this.text = ''; }, 3000); }) }, methods: { handleIncrement() { this.count += parseInt(this.entry, 10); eventBus.$emit('count-incremented') this.entry = 0; }, handleDecrement() { this.count -= parseInt(this.entry, 10); eventBus.$emit('count-decremented') this.entry = 0; } } })
You may have noticed that we’re about to hop on the event bus by looking at that code.
First thing we’ve got to do is establish a path for sending an event from one component to another. We can pave that path using eventBus.$emit() (with emit being a fancy word for sending out). That sending is included in two methods, handleIncrement and handleDecrement, which is listening for the input submissions. And, once they happen, our event bus races to any component requesting data and sends the props over.
Tumblr media
You may have noticed that we are listening for both events in the created() lifecycle hook using eventBus.$on(). In both events, we have to pass in the string that corresponds to the event we emitted. This is like an identifier for the particular event and the thing that established a way for a component to receive data. When eventBus recognizes a particular event that has been announced, the function that follows is called — and we set a text to display what had happened, and make it it disappear after three seconds.
Practice task: Handling multiple components
Let’s say we are working on a profile page where users can update their name and email address for an app and then see the update without refreshing the page. This can be achieved smoothly using event bus, even though we are dealing with two components this time: the user profile and the form that submits profile changes.
See the Pen Vuejs Event Bus 2 by Kingsley Silas Chijioke (@kinsomicrote) on CodePen.
Here is the template:
<div class="container"> <div id="profile"> <h2>Profile</h2> <div> <p>Name: </p> <p>Email: </p> </div> </div> <div id="edit__profile"> <h2>Enter your details below:</h2> <form @submit.prevent="handleSubmit"> <div class="form-field"> <label>Name:</label> <input type="text" v-model="user.name" /> </div> <div class="form-field"> <label>Email:</label> <input type="text" v-model="user.email" /> </div> <button>Submit</button> </form> </div> </div>
We will pass the ids (user.name and user.email)to the corresponding component. First, let’s set up the template for the Edit Profile (edit__profile) component, which holds the name and email data we want to pass to the Profile component we’ll set up next. Again, we’ve established an event bus to emit that data after it detects that a submission event has taken place.
new Vue({ el: "#edit__profile", data() { return { user: { name: '', email: '' } } }, methods: { handleSubmit() { eventHub.$emit('form-submitted', this.user) this.user = {} } } })
This data will be used to reactively update the profile on the user in the Profile (profile) component, which looking for name and email to come in when the bus arrives to its hub.
new Vue({ el: '#profile', data() { return { name: '', email: '' } }, created() { eventHub.$on('form-submitted', ({ name, email}) => { this.name = name; this.email = email }) } })
Their bags are packed. Now all they have to do is go home.
Pretty cool, right? Even though the Edit Profile and Profile components are unrelated — or not in a direct parent-child relationship) — it is possible for them to communicate with each other, linked by the same event.
Rollin’ right along
I have found Event Bus helpful in cases where I want to enable reactivity in my app — specifically, to update a component based on the response obtained from the server without causing the page to refresh. It is also possible that the event that gets emitted can be listened to by more than one component.
If you have other interesting scenarios of using event bus, I’ll love to hear about them in the comments. 🚌
The post Using Event Bus to Share Props Between Vue Components appeared first on CSS-Tricks.
😉SiliconWeb Dev. | 🌐CSS-Tricks
0 notes
t-baba · 8 years ago
Photo
Tumblr media
Get Started With Vue Router
Introduction
Routing becomes an important feature to put in place when you have many components. Thanks to the awesome Vue.js team, this is easy using vue-router.
In this tutorial, you will see how to use vue-router while building a simple Vue.js application.
Set Up the Application
You will make use of Vue-CLI to set up your application for this tutorial. If you do not have it installed already on your machine, you can do so by running:
npm install -g vue-cli
With that done, you can set up your application using the command below.
vue init webpack router-app
You are going to be asked some questions. One of these questions is: Install vue-router? For that, enter y.
Navigate to your project folder from your terminal:
cd router-app
Run the command to install all dependencies:
npm install
Start your development server by running:
npm run dev
If you want to install vue-router manually, you can use the command below.
npm install vue-router --save
Integrate Vue-Router
When using Vue-CLI, the router gets activated by default. You can see that in your src/router/index.js file.
#src/router/index.js import Vue from 'vue' // 1 import Router from 'vue-router' // 2 import HelloWorld from '@/components/HelloWorld' // 3 Vue.use(Router) // 4 export default new Router({ // 5 routes: [ { path: '/', name: 'Hello', component: HelloWorld } ] })
Vue is imported from vue.
Router is imported from the vue-router package.
HelloWorld is imported from the components folder. We'll talk more about this later.
Router is mounted as middleware to your project.
A default route configuration is created. The route is an array of a JavaScript object. It consists of a path, name, and component. The path gets appended to the URL of your web application. The route created above is meant for the home page. You can change the path to /hello, and it will no longer work for the home page. It will only be triggered when you visit the /hello path of your application. The component tells the route the component you want to load when that path is visited. This is the reason you imported the HelloWorld component. This route is exported as Router.
The exported Router has to be imported in your src/main.js file. This is important for the routes to work. This is taken care of when working with Vue-CLI. Your src/main.js should look like this:
#src/main.js // The Vue build version to load with the `import` command // (runtime-only or standalone) has been set in webpack.base.conf with an alias. import Vue from 'vue' import App from './App' import router from './router' // 1 Vue.config.productionTip = false /* eslint-disable no-new */ new Vue({ el: '#app', router, // 2 template: '<App/>', components: { App } })
The router is imported from your router folder.
The imported router is used when creating a new Vue instance.
Standard Routes
The route you saw above is an example of a standard route. A standard route is one having a path, component, and name. Let's create our own route. Try this part out yourself using the flow below.
Create a new component called Pack. You need to have some dummy text.
Go to your src/router/index.js, import the new component you created, and add a new path.
Open your browser and point to the new path.
I bet you were able to do that on your own. Let's try it out together.
Here is what my Pack component looks like.
#src/components/Pack.vue <template> <div class="hello"> <h1>Pack Component</h1> <p>This is a pack component. It is supposed to be a pack of wolves, but the wolves got trap in this tiny component</p> </div> </template> <script> export default { } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Open your router file, and it should be looking like this.
#src/router/index.js import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Pack from '@/components/Pack' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: HelloWorld }, { path: '/pack', name: 'Pack', component: Pack } ] })
Now point your browser to http://localhost:8080/#/pack and you should see your new page.
Routes With Parameters
The routes you have made so far are static routes. Let's see how to make dynamic routes. Open your routes file and add another route like this.
#src/router/index.js { path: '/user/:id', component: User }
Here you have your path set to /user/:id; the :id defines a parameter that allows you to pass values to the routes via the URL. From the above, it is possible to have http://localhost:8080/user/23.
The value passed to the route component, in this case, is 23, and this can be accessed in the User component.
To try this out, create a new component called User. In this component, you want to be able to access the route parameter passed through the URL. This parameter will be saved in a variable called id, and the value outputted in the template. Here is what the component should look like.
#src/components/User.vue <template> <div> <h1>User Component</h1> <p>The loaded id is: </p> <router-view></router-view> </div> </template> <script> export default { name: 'user', data () { return { id: this.$route.params.id } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Now point your browser to http://localhost:8080/#/user/123 and you will see the parameter displayed. Change from 123 to something else, and the new value will be displayed.
Child Routes
In Vue.js, it is possible to nest routes by defining children routes. This is possible using the children property provided by Vue.js. The children routes are passed as an array of objects. In your test app, you will create a child route for profiles. The child route will be given a path and a component.
First, create a new component called Profile.vue. Here is what it should look like.
#src/components/Profile.vue <template> <div> <h1>User Profile Component</h1> <p>This is a user profile</p> </div> </template> <script> export default { name: 'profile', data () { return { } } } </script> <!-- Add "scoped" attribute to limit CSS to this component only --> <style scoped> </style>
Open your router file. The first thing you want to do will be to import the Profile component. After doing that, add the children property to the route for the User component so your route file looks like this.
#src/router/index.js import Vue from 'vue' import Router from 'vue-router' import HelloWorld from '@/components/HelloWorld' import Pack from '@/components/Pack' import User from '@/components/User' import Profile from '../components/Profile' Vue.use(Router) export default new Router({ routes: [ { path: '/', name: 'Hello', component: HelloWorld }, { path: '/pack', name: 'Pack', component: Pack }, { path: '/user/13', component: User, children: [ { path: 'profile', component: Profile } ] } ] })
Now you will be able to access this new component when you point your browser to http://localhost:8080/#/user/13/profile.
Link to Routes
At this moment, the only way to navigate in your application is by entering the URL path in the browser. This is not how you will want to build a real-world application. To link to routes in Vue.js, you'll have to make use of the <router-link> element.
Here is how it is used:
<router-link to="/route-path">Link to the route</router-link>
For children routes, here is what it should look like.
<router-link to="/parent-route/child-route">Links to the child route</router-link>
The to attribute contains the path to the route.
To set that up in your application, open your App.vue file and make it look like this.
#src/App.vue <template> <div id="app"> <img src="./assets/logo.png"> <div> <ul> <li><router-link to="/">Home</router-link></li> <li><router-link to="/pack">Pack</router-link></li> <li><router-link to="/user/13">User</router-link></li> <li><router-link to="/user/13/profile">Profile</router-link></li> </ul> </div> <router-view/> </div> </template> <script> export default { name: 'app' } </script> <style> #app { font-family: 'Avenir', Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
Conclusion
Navigating from one view to another is now very easy. You can go ahead and add more views. Try adding a child route to the profile route, so the path becomes http://localhost:8080/#/user/13/profile/child-path.
In this tutorial, you learned how to set up routing in Vue.js. Going forward, you should have no issues with routing in a Vue.js application. While working on this application, you also learned about the route and params object.
I hope you enjoyed yourself.
by Chinedu Izuchukwu via Envato Tuts+ Code http://ift.tt/2ABGsc6
0 notes
t-baba · 8 years ago
Photo
Tumblr media
Getting Started with React: A Beginner’s Guide
In this guide, I'll show you the fundamental concepts of React by taking you through a practical, step-by-step tutorial on how to create a simple Message App using React. I'll assume you have no previous knowledge of React. However, you'll need at least to be familiar with modern JavaScript and NodeJS.
React is a remarkable JavaScript library that's taken the development community by storm. In a nutshell, it's made it easier for developers to build interactive user interfaces for web, mobile and desktop platforms. One of its best features is its freedom from the problematic bugs inherent in MVC frameworks, where inconsistent views is a recurring problem for big projects. Today, thousands of companies worldwide are using React, including big names such as Netflix and AirBnB. React has become immensely popular, such that a number of apps have been ported to React --- including WhatsApp, Instagram and Dropbox.
Prerequisites
As mentioned, you need some experience in the following areas:
functional JavaScript
object-oriented JavaScript
ES6 JavaScript Syntax
On your machine, you'll need:
a NodeJS environment
a Yarn setup (optional)
If you'd like to take a look first at the completed project that's been used in this guide, you can access it via GitHub.
[affiliate-section title="Recommended Courses"][affiliate-card title="The Best Way to Learn React for Beginners" affiliatename="Wes Bos" text="A step-by-step training course to get you building real world React.js + Firebase apps and website components in a couple of afternoons. Use coupon code 'SITEPOINT' at checkout to get 25% off." url="http://ift.tt/2tF1ast" imageurl="http://ift.tt/2y2HI7v"][/affiliate-section]
What is React?
React is a JavaScript library for building UI components. Unlike more complete frameworks such as Angular or Vue, React deals only with the view layer. Hence, you'll need additional libraries to handle things such as data flow, routing, authentication etc. In this guide, we'll focus on what React can do.
Building a React project involves creating one or more React components that can interact with each other. A React component is simply a JavaScript class that requires the render function to be declared. The render function simply outputs HTML code, which is implemented using either JSX or JavaScript code. A React component may also require additional functions for handling data, actions and lifecyle events.
React components can further be categorized into containers/stateful components and stateless components. A stateless component's work is simply to display data that it receives from its parent React component. It can also receive events and inputs, which it passes up to its parent to handle. A React container or stateful component does the work of rendering one or more child components. It fetches data from external sources and feeds it to its child components. It also receives inputs and events from them in order to initiate actions.
Understanding the React DOM
Before we get to coding, you need to be aware that React uses a Virtual DOM to handle page rendering. If you're familiar with jQuery, you know that it can directly manipulate a web page via the HTML DOM. In a lot of use cases, this direct interaction poses little to no problems. However, for certain cases, such as the running of a highly interactive, real-time web application, performance often takes a huge hit.
To counter this, the concept of the Virtual DOM was invented, and is currently being applied by many modern UI frameworks including React. Unlike the HTML DOM, the Virtual DOM is much easier to manipulate, and is capable of handling numerous operations in milliseconds without affecting page performance. React periodically compares the Virtual DOM and the HTML DOM. It then computes a diff, which it applies to the HTML DOM to make it match the Virtual DOM. This way, React does its best to ensure your application is rendered at a consistent 60 frames per second, meaning that users experience little or no lag.
Enough chitchat! Let's get our hands dirty …
Start a Blank React Project
As per the prerequisites, I assume you already have a NodeJS environment setup. Let's first install or update npm to the latest version.
$ npm i -g npm
Next, we're going to install a tool, Create React App, that will allow us to create our first React project:
$ npm i -g create-react-app
Navigate to your project's root directory and create a new React project using the tool we just installed:
$ create-react-app message-app … Success! Created message-app at /home/mike/Projects/github/message-app Inside that directory, you can run several commands: yarn start Starts the development server. yarn build Bundles the app into static files for production. yarn test Starts the test runner. yarn eject Removes this tool and copies build dependencies, configuration files and scripts into the app directory. If you do this, you can’t go back! We suggest that you begin by typing: cd message-app yarn start Happy hacking!
Depending on the speed of your internet connection, this might take a while to complete if this is your first time running the create-react-app command. A bunch of packages gets installed along the way, which are needed to set up a convenient development environment --- including a web server, compiler and testing tools.
Navigate to the newly created message-app folder and open the package.json file.
{ "name": "message-app", "version": "0.1.0", "private": true, "dependencies": { "react": "^15.6.1", "react-dom": "^15.6.1", "react-scripts": "1.0.12" }, "scripts": { "start": "react-scripts start", "build": "react-scripts build", "test": "react-scripts test --env=jsdom", "eject": "react-scripts eject" } }
Surprise! You expected to see a list of all those packages listed as dependencies, didn't you? Create React App is an amazing tool that works behind the scenes. It creates a clear separation between your actual code and the development environment. You don't need to manually install Webpack to configure your project. Create React App has already done it for you, using the most common options.
Let's do a quick test run to ensure our new project has no errors:
$ yarn start Starting development server… Compiled successfully! You can now view message-app in the browser. Local: http://localhost:3000/ On Your Network: http://10.0.2.15:3000/ Note that the development build is not optimized. To create a production build, use yarn build.
If you don't have Yarn, just substitute with npm like this: npm start. For the rest of the article, use npm in place of yarn if you haven't installed it.
Your default browser should launch automatically, and you should get a screen like this:
One thing to note is that Create React App supports hot reloading. This means any changes we make on the code will cause the browser to automatically refresh. For now, let's first stop the development server by pressing Ctrl + C. This step isn't necessary, I'm just showing you how to kill the development server. Once the server has stopped, delete everything in the src folder. We'll create all the code from scratch so that you can understand everything inside the src folder.
Introducing JSX Syntax
Inside the src folder, create an index.js file and place the following code in it:
import React from 'react'; import ReactDOM from 'react-dom'; ReactDOM.render(<h1>Hello World</h1>, document.getElementById('root'));
Start the development server again using yarn start or npm start. Your browser should display the following content:
This is the most basic "Hello World" React example. The index.js file is the root of your project where React components will be rendered. Let me explain how the code works:
Line 1: React package is imported to handle JSX processing
Line 2: ReactDOM package is imported to render React components.
Line 4: Call to render function
<h1>Hello World</h1>: a JSX element
document.getElementById('root'): HTML container
The HTML container is located in public/index.html file. On line 28, you should see <div id="root"></div>. This is known as the root DOM because everything inside it will be managed by the React DOM.
JSX (JavaScript XML) is a syntax expression that allows JavaScript to use tags such as <div>, <h1>, <p>, <form>, and <a>. It does look a lot like HTML, but there are some key differences. For example, you can't use a class attribute, since it's a JavaScript keyword. Instead, className is used in its place. Also, events such as onclick are spelled onClick in JSX. Let's now modify our Hello World code:
const element = <div>Hello World</div>; ReactDOM.render(element, document.getElementById('root'));
I've moved out the JSX code into a variable named element. I've also replaced the h1 tags with div. For JSX to work, you need to wrap your elements inside a single parent tag. This is necessary for JSX to work. Take a look at the following example:
const element = <span>Hello,</span> <span>Jane</span;
The above code won't work. You'll get a syntax error telling you must enclose adjacent JSX elements in an enclosing tag. Basically, this is how you should enclose your elements:
const element = <div> <span>Hello, </span> <span>Jane</span> </div>;
How about evaluating JavaScript expressions in JSX? Simple, just use curly braces like this:
const name = "Jane"; const element = <p>Hello, {name}</p>
… or like this:
const user = { firstName: "Jane", lastName: "Doe" } const element = <p>Hello, {user.firstName} {user.lastName}</p>
Update your code and confirm that the browser is displaying "Hello, Jane Doe". Try out other examples such as { 5 + 2 }. Now that you've got the basics of working with JSX, let's go ahead and create a React component.
Continue reading %Getting Started with React: A Beginner’s Guide%
by Michael Wanyoike via SitePoint http://ift.tt/2f3OnKa
0 notes