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 |
---|---|
21 | |
21 | |
9 | |
7 | |
6 |
Explore the 30-30-30 rule, a dynamic social media strategy for new businesses. Learn how t...
By Trevor Sep 20, 2023Discover how to leverage the often overlooked footer of your ecommerce site to gain custom...
By Skye Sep 15, 2023In this blog, we’ll be shining a light on Shopify Partners, Experts, and Affiliates. Who a...
By Imogen Sep 13, 2023