Categories
Vue 3

Add a Swiper Carousel into a Vue 3 App with Swiper 6

Swiper for Vue.js lets us add a carousel to our Vue 3 app.

In this article, we’ll look at how to add a carousel into our Vue 3 app with Swiper.

Installation

We can install the Swiper package by running:

npm i swiper

Basic Usage

Once we installed the package, we can add a slider by writing:

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="onSwiper"
    @slideChange="onSlideChange"
  >
    <swiper-slide v-for="n of 50" :key="n">Slide {{ n }}</swiper-slide>
  </swiper>
</template>
<script>
import { Swiper, SwiperSlide } from "swiper/vue";
import 'swiper/swiper-bundle.css'

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  methods: {
    onSwiper(swiper) {
      console.log(swiper);
    },
    onSlideChange() {
      console.log("slide change");
    },
  },
};
</script>

We add the swiper component to add the slider.

slides-per-view lets us set the number of slides to show per view.

space-between has the space between slides in pixels.

It emits the swiper event which is emitted when the slider is created.

slideChange event is emitted when we change slides.

We import the swiper/swiper-bundle.css file to add styles for the slides.

swiper-slide has the slides for the slider.

We can add the zoom prop to enable additional wrapper for zoom mode if it’s set to true .

virtualIndex has the index for virtual slides.

SwiperSlide Slot Props

We can get some data from the swiper-slide ‘s component’s slot props.

For example, we get the isActive prop to see if the slide is active:

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="onSwiper"
    @slideChange="onSlideChange"
  >
    <swiper-slide v-slot="{ isActive }" v-for="n of 50" :key="n"
      >Slide {{ n }} {{ isActive ? "active" : "not active" }}</swiper-slide
    >
  </swiper>
</template>
<script>
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  methods: {
    onSwiper(swiper) {
      console.log(swiper);
    },
    onSlideChange() {
      console.log("slide change");
    },
  },
};
</script>

It also provides the isPrev slot prop to see whether a slide is a slide previous to the active one.

The isNext slot prop to see whether a slide is a slide next to the active one.

isVisible indicates whether the current slide is visible.

isDuplicate indicates whether the slide is a duplicate slide.

Slots

We can populate slots provided by the swiper component.

For instance, we can write:

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="onSwiper"
    @slideChange="onSlideChange"
  >
    <swiper-slide v-for="n of 50" :key="n">Slide {{ n }}</swiper-slide>
    <template v-slot:container-start>
      <span>Container Start</span>
    </template>
    <template v-slot:container-end>
      <span>Container End</span>
    </template>
    <template v-slot:wrapper-start>
      <span>Wrapper Start</span>
    </template>
    <template v-slot:wrapper-end>
      <span>Wrapper End</span>
    </template>
  </swiper>
</template>
<script>
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  methods: {
    onSwiper(swiper) {
      console.log(swiper);
    },
    onSlideChange() {
      console.log("slide change");
    },
  },
};
</script>

We populate the container-start slot to add content to the top of the slider container.

container-end adds content to the bottom of the slider container

wrapper-start adds content before the first slide.

wrapper-end adds content after the last slide.

Conclsion

We can add sliders into our Vue 3 app with Swiper 6.

Categories
Vue 3

Add a Swiper Carousel into a Vue 3 App with Swiper 6

Swiper for Vue.js lets us add a carousel to our Vue 3 app.

In this article, we’ll look at how to add a carousel into our Vue 3 app with Swiper.

Virtual Slides

We can add virtual slides, which are slides that are rendered completely by Vue 3.

It doesn’t require anything except the virtual prop.

For instance, we can write:

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="onSwiper"
    @slideChange="onSlideChange"
    virtual
  >
    <swiper-slide v-for="n of 50" :virtualIndex="n" :key="n"
      >Slide {{ n }}</swiper-slide
    >
  </swiper>
</template>
<script>
import SwiperCore, { Virtual } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

SwiperCore.use([Virtual]);

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  methods: {
    onSwiper(swiper) {
      console.log(swiper);
    },
    onSlideChange() {
      console.log("slide change");
    },
  },
};
</script>

to add the swiper component that renders virtual slides.

Also, we have to add SwiperCore.use([Virtual]) to add the Virtual plugin so that we can render virtual slides.

Controller

We can add a slider that’s controlled by another slider.

For instance, we can write:

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="setControlledSwiper"
  >
    <swiper-slide v-for="n of 50" :virtualIndex="n" :key="n"
      >Slide {{ n }}</swiper-slide
    >
  </swiper>

  <swiper :controller="{ control: controlledSwiper }">
    <swiper-slide v-for="n of 50" :virtualIndex="n" :key="n"
      >Slide {{ n }}</swiper-slide
    >
  </swiper>
</template>

<script>
import SwiperCore, { Controller } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

SwiperCore.use([Controller]);

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  data() {
    return {
      controlledSwiper: null,
    };
  },
  methods: {
    setControlledSwiper(swiper) {
      this.controlledSwiper = swiper;
    },
  },
};
</script>

The first swiper controls the behavior of the 2nd swiper.

We do this by calling the setControlledSwiper method when the first swiper is initialized.

In the method, we just set swiper as the value of this.controlledSwiper .

Now in the 2nd swiper , we pass in an object with the control property set to controlledSwiper into the controller prop to let the first swiper control the 2nd one.

We also have to addSwiperCore.use([Controller]) to let us add controlled swipers.

Also, we can add 2-way control to swipers.

For instance, we can write:

<template>
  <swiper
    :slides-per-view="3"
    :space-between="50"
    @swiper="setFirstSwiper"
    :controller="{ control: secondSwiper }"
  >
    <swiper-slide v-for="n of 50" :virtualIndex="n" :key="n"
      >Slide {{ n }}</swiper-slide
    >
  </swiper>

  <swiper @swiper="setSecondSwiper" :controller="{ control: firstSwiper }">
    <swiper-slide v-for="n of 50" :virtualIndex="n" :key="n"
      >Slide {{ n }}</swiper-slide
    >
  </swiper>
</template>

<script>
import SwiperCore, { Controller } from "swiper";
import { Swiper, SwiperSlide } from "swiper/vue";
import "swiper/swiper-bundle.css";

SwiperCore.use([Controller]);

export default {
  components: {
    Swiper,
    SwiperSlide,
  },
  data() {
    return {
      firstSwiper: null,
      secondSwiper: null,
    };
  },
  methods: {
    setFirstSwiper(swiper) {
      this.firstSwiper = swiper;
    },
    setSecondSwiper(swiper) {
      this.secondSwiper = swiper;
    },
  },
};
</script>

We have the setFirstSwiper and setSecondSwiper to set the firstSwiper and secondSwiper reactive properties respectively.

Then we pass them as values of the controller prop to enable control of them.

Now when we swipe one of the sliders, the other one will change.

Conclusion

We can add more complex sliders into our Vue 3 app with Swiper 6.

Categories
Vue 3

Create Vue 3 Apps with the Composition API — Custom Refs and Shallow Reactivity

It lets us extract logic easily an not have to worry about the value of this in our code.

It also works better with TypeScript because the value of this no longer has to be typed.

In this article, we’ll look at how to create Vue 3 apps with the Composition API.

customRef

We can use the customRef function to create a custom ref.

For instance, we can write:

<template>
  <div>
    <input v-model="text" />
    {{ text }}
  </div>
</template>

<script>
import { customRef } from "vue";

const useDebouncedRef = (value, delay = 200) => {
  let timeout;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newValue) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          value = newValue;
          trigger();
        }, delay);
      },
    };
  });
};

export default {
  name: "App",
  setup() {
    return {
      text: useDebouncedRef("hello world"),
    };
  },
};
</script>

We create the useDebounceRef function that returns a custom ref created bu the customRef function.

It takes a callback with the track function to track the value.

And the setter calls trigger to trigger state updates.

We ser the value in the setter to newValue so that the items are updated.

markRaw

We can call the markRaw function to mark an object so that it’ll never be converted to a proxy.

For instance, we can write:

<template>
  <div></div>
</template>

<script>
import { isReactive, markRaw, reactive } from "vue";

export default {
  name: "App",
  setup() {
    const foo = markRaw({});
    console.log(isReactive(reactive(foo)));
    return { foo };
  },
};
</script>

The console log logs false since we called markRaw to disable reactivity on the object we passed into it.

But if we mark one object as raw and we reference that object in another object, then they’ll be considered not to be equal even though they have the same reference:

<template>
  <div></div>
</template>

<script>
import { isReactive, markRaw, reactive } from "vue";

export default {
  name: "App",
  setup() {
    const foo = markRaw({
      nested: {},
    });

    const bar = reactive({
      nested: foo.nested,
    });

    console.log(foo.nested === bar.nested);
    return { foo };
  },
};
</script>

We set bar.nested to foo.nested , but the console log is false .

shallowReactive

We can create a shallow reactive object with the shallowReactive function.

The reactive property is limited to the top-level properties of the object.

For instance, we can write:

<template>
  <div>
    <button @click="increment">increment</button>
    {{ state.foo }}
    {{ state.nested.bar }}
  </div>
</template>

<script>
import { isReactive, shallowReactive } from "vue";

export default {
  name: "App",
  setup() {
    const state = shallowReactive({
      foo: 1,
      nested: {
        bar: 2,
      },
    });

    const increment = () => {
      state.foo++;
      state.nested.bar++;
    };
    console.log(isReactive(state.nested.bar));
    return { state, increment };
  },
};
</script>

In the increment function, we increment both state.foo and state.nested.bar and they’ll both update in the template.

But when we log state.nested.bar with isReactive , we get false logged.

Since it’s not reactive, it won’t trigger watchers to run:

<template>
  <div>
    <button @click="increment">increment</button>
    {{ state.foo }}
    {{ state.nested.bar }}
  </div>
</template>

<script>
import { isReactive, shallowReactive, watch } from "vue";

export default {
  name: "App",
  setup() {
    const state = shallowReactive({
      foo: 1,
      nested: {
        bar: 2,
      },
    });

    const increment = () => {
      state.foo++;
      state.nested.bar++;
    };

    watch(state.nested.bar, (bar) => {
      console.log(bar);
    });

    return { state, increment };
  },
};
</script>

Then watch callback in the 2nd argument won’t run when state.nested.bar is updated.

Conclusion

We can use various functions provided Vue 3’s composition API to create various kinds of reactive and non-reactive properties.

Categories
Vue 3

Create Vue 3 Apps with the Composition API — Check Reactive Properties

It lets us extract logic easily an not have to worry about the value of this in our code.

It also works better with TypeScript because the value of this no longer has to be typed.

In this article, we’ll look at how to create Vue 3 apps with the Composition API.

toRefs

We can use the toRefs function to convert a ref toa plain object.

For instance, we can write:

<template>
  <div></div>
</template>

<script>
import { reactive, toRefs } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      foo: 1,
      bar: 2,
    });

    const stateAsRefs = toRefs(state);
    console.log(stateAsRefs);

    return {
      state,
    };
  },
};
</script>

to convert the state reactive property to a plain object.

state.foo and stat.bar are reactive properties with values being the values that we set in the reactive function.

isRef

The isRef function checks if a variable is a ref.

For instance, we can write:

<template>
  <div></div>
</template>

<script>
import { isRef, reactive, ref } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      foo: 1,
      bar: 2,
    });

    const r = ref(0);
    console.log(isRef(state));
    console.log(isRef(r));

    return {
      state,
    };
  },
};
</script>

We call isRef with state , which returns false .

And when we call isRef with r , it returns true .

isProxy

The isProxy function checks if an object is reactive or read-only.

For instance, we can write:

<template>
  <div></div>
</template>

<script>
import { isProxy, reactive, readonly, ref } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      foo: 1,
      bar: 2,
    });
    const ro = readonly({ foo: 1 });

    const r = ref(0);
    console.log(isProxy(state));
    console.log(isProxy(ro));
    console.log(isProxy(r));

    return {
      state,
    };
  },
};
</script>

The first 2 console logs are log true since we created variables with reactive and readonly .

And the 3rd one logs false since a ref isn’t created with reactive or readonly .

isReactive

We can check if a variable is created from reactive with isReactive .

For instance, we can write:

<template>
  <div></div>
</template>

<script>
import { isReactive, reactive, readonly, ref } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      foo: 1,
      bar: 2,
    });
    const ro = readonly({ foo: 1 });

    const r = ref(0);
    console.log(isReactive(state));
    console.log(isReactive(ro));
    console.log(isReactive(r));

    return {
      state,
    };
  },
};
</script>

Only state is created with the reactive function, so only the first console log logs true .

isReadonly

We can check if a variable is created with readonly is isReadonly .

For instance, we can write:

<template>
  <div></div>
</template>

<script>
import { isReadonly, reactive, readonly, ref } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      foo: 1,
      bar: 2,
    });
    const ro = readonly({ foo: 1 });

    const r = ref(0);
    console.log(isReadonly(state));
    console.log(isReadonly(ro));
    console.log(isReadonly(r));

    return {
      state,
    };
  },
};
</script>

to call isReadonly .

Only the 2nd console log logs true since only ro is created with readonly .

Conclusion

We can use various functions from the Vue 3 composition API to do various checks on reactive properties.

Categories
Vue 3

Create Vue 3 Apps with the Composition API — Refs

It lets us extract logic easily an not have to worry about the value of this in our code.

It also works better with TypeScript because the value of this no longer has to be typed.

In this article, we’ll look at how to create Vue 3 apps with the Composition API.

Using Refs with v-for

We can assign refs to items rendered with v-for .

For instance, we can write:

<template>
  <div
    v-for="(item, i) in list"
    :ref="
      (el) => {
        divs[i] = el;
      }
    "
    :key="i"
  >
    {{ item }}
  </div>
</template>

<script>
import { ref, reactive, onBeforeUpdate } from "vue";

export default {
  setup() {
    const list = reactive([1, 2, 3]);
    const divs = ref([]);

    onBeforeUpdate(() => {
      divs.value = [];
    });

    return {
      list,
      divs,
    };
  },
};
</script>

We create the divs reactive property with the ref function.

Then when we render the items with v-for , we assign the el HTML element object as an entry of the divs array.

Reactivity Utilities

The Vue 3 composition API comes with some utility functions to do various things with reactive properties.

unref

The unref function lets us return the ref’s value or the argument we pass into the ref function depending on if the variable is a ref.

For instance, we can write:

<template>
  <div>
    <button @click="increment">increment</button>
    {{ count }}
  </div>
</template>

<script>
import { ref, unref, watch } from "vue";
export default {
  name: "App",
  setup() {
    const count = ref(0);
    const increment = () => {
      count.value++;
    };
    watch(count, () => {
      console.log(unref(count));
    });

    return {
      count,
      increment,
    };
  },
};
</script>

We create the count reactive property.

And in the watch callback, we call unref(count) to get the actual value of the count reactive property.

If it’s not a ref, it returns the value of the variable we pass in.

toRef

The toRef function lets us create a ref for a property on a reactive source object.

For instance, we can write:

<template>
  <div>
    <button @click="increment">increment</button>
    {{ count }}
    {{ state.count }}
  </div>
</template>

<script>
import { reactive, toRef } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      count: 1,
    });

    const count = toRef(state, "count");
    const increment = () => {
      state.count++;
    };

    return {
      state,
      count,
      increment,
    };
  },
};
</script>

We call toRef to create a ref from the state.count property.

Now we can include it in the object we return and then reference it in the template.

This is useful if we want to pass it into a composition function.

For instance, we can write:

<template>
  <div>
    <button @click="increment">increment</button>
    {{ count }}
    {{ state.count }}
  </div>
</template>

<script>
import { reactive, toRef, watch } from "vue";
export default {
  name: "App",
  setup() {
    const state = reactive({
      count: 1,
    });

    const count = toRef(state, "count");
    const increment = () => {
      state.count++;
    };

    watch(count, (count) => console.log(count));

    return {
      state,
      count,
      increment,
    };
  },
};
</script>

We pass the count into watch so we can watch its value.

Conclusion

We can assign refs to HTML elements to let us access them in our component.

And we can manipulate refs with various functions that comes with Vue 3’s composition API.