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');
User | RANK |
---|---|
35 | |
24 | |
17 | |
9 | |
9 |
Photo by Marco Verch Sales channels on Shopify are various platforms where you can sell...
By Ollie May 25, 2023Summary of EventsBeginning in January of 2023, some merchants reported seeing a large amo...
By Trevor May 15, 2023With 2-Factor Authentication being required to use Shopify Payments, we’re here to help yo...
By Imogen Apr 26, 2023