Liquid, JavaScript, themes, sales channels
Hi.
I have a question about what happens when I change a Variant using new Shopify.OptionSelectors().
I tried to implement it with reference to the document.
https://shopify.dev/themes/product-merchandising/variants
When the variant is changed in the select tag, [?Variant=] is added to the end of the URL, the amount and product name displayed on the page will not be changed.
Since I am getting the product object with product.selected_or_first_available_variant, the amount and product name will change when I reload the page. Do I have to implement the page reload functions by myself? Or is it prepared by shopify like [?Variant=]?
I'm not good at English, so if you don't understand the meaning, please let me know.
thank you.
Hello @tsu_bi ,
Can you please provide your store url ?
this site is my original theme for development. using Vue.js.
source code
// eslint-disable-next-line import/no-extraneous-dependencies
import Vue from 'vue/dist/vue.min';
import axios from 'axios';
new Vue({
delimiters: ['${', '}'],
data() {
return {
data: '',
productSelect: '',
productQuantity: 1,
productData: {},
activeNotification: false,
activeNotificationMsg: '',
};
},
created() {
const currentUrl = new URL(window.location.href);
const params = currentUrl.searchParams;
params.delete('variant');
const productUrl = currentUrl.href;
axios
.get(`${productUrl}.js`)
.then((res) => {
this.data = res.data;
// eslint-disable-next-line no-new,no-undef
new Shopify.OptionSelectors('product-select', {
product: res.data,
onVariantSelected: this.selectCallback,
enableHistoryState: true,
});
})
.catch((err) => {
console.log(err);
});
},
mounted() {
this.init();
},
methods: {
init() {
this.productSelect = this.$refs.productSelect;
this.productData = {
id: this.productSelect.value,
quantity: this.productQuantity,
};
},
changeQuantity() {
this.productData.quantity = this.productQuantity;
},
addToCart(e) {
e.preventDefault();
axios
.post('/cart/add.js', this.productData)
.then(() => {
this.activeNotification = true;
this.activeNotificationMsg = 'added.';
})
.catch(() => {
this.activeNotification = true;
this.activeNotificationMsg = 'error.';
});
setTimeout(() => {
this.activeNotification = false;
}, 3000);
},
// eslint-disable-next-line no-unused-vars
selectCallback(variant, selector) {
this.productData.id = variant.id;
},
},
}).$mount('#product');
Learn these 5 things I had to learn the hard way with starting and running my own business
By Kitana Jan 27, 2023Would you love to unleash the unbridled power of the Google Shopping Channel into your sho...
By Gabe Jan 6, 2023How can you turn a hobby into a career? That’s what Emmanuel did while working as a wa...
By Skye Dec 30, 2022