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');
Are you ready to take your business to the next level? Look no further than the latest ...
By SarahF_Shopify Apr 15, 2024We’re keeping the ball rolling to make sure you’re always ahead of the game. So buckle ...
By JasonH Apr 8, 2024Portrait of Stephen positioned next to an image of planet Earth, with the Stephen's World ...
By JasonH Mar 18, 2024