Posted: January 29, 2021
Updated: February 27, 2021
Single file component script
import MyMixin from 'MyMixin.js';
import OtherComponent from 'OtherComponent.vue';
import { mapActions, mapGetters, mapMutations, mapState } from 'vuex';
export default {
name: 'MyComponent',
components: {
OtherComponent
},
mixins: [
MyMixin,
],
data() {
return {
foo: '',
bar: {}
}
},
props: {
'label': {
type: String,
required: false,
default: ''
},
'elephant': {
type: Object,
required: false,
default: null
},
'weight': {
type: Number,
required: true
},
'hasTrunk': { // has-trunk in parent component DOM
type: Boolean,
required: true
}
}
computed: {
// mapState, mapGetter etc take an Array of Strings OR
// an Object to change local variable name
...mapState('mystore', [
'foo',
]),
...mapGetters('otherstore', {
localFoo: 'foo',
localBar: 'bar'
}),
canSmell() {
return this.hasTrunk;
},
localWeight: {
get() {
return this.weight || null;
},
set(newVal) {
if (newVal !== null)
this.$emit('weight_update', newVal);
}
}
},
methods: {
doSomething() {
this.label = 'HAHA!';
return;
}
},
watch: {
someVariable(newValue) {
console.log(newValue);
}
},
// lifecycle hooks in order of execution: https://vuejs.org/v2/guide/instance.html#Instance-Lifecycle-Hooks
beforeCreate() {
this.doSomething();
},
created() {
},
beforeMount() {
},
mounted() {
},
beforeDestroy() {
},
destroyed() {
}
Stores
const state = {
elephant: {},
donkey: null
};
const getters = {
hasElephant: (state) => {
if (state.elephant.id)
return true;
return false;
},
needsWater: (state) => (species) => {
return state[species].needs_water;
},
elephantNeedsWater: (state, getters) => {
if (!getters.hasElephant)
return false;
return getters.elephantNeedsResource('water');
},
elephantNeedsResource: (state, getters) => (resource) => {
if (!getters.hasElephant)
return false;
if (resource === 'water')
return getters.needsWater('elephant');
return false;
}
};
const actions = {
// commit is to commit mutations
// dispatch is to call another action
deleteAnimal({ commit, dispatch, getters, rootState, state }, species) {
commit('nullifyAnimal', species);
dispatch('harmless');
},
harmless({ commit }) {
return;
}
};
const mutations = {
nullifyAnimal(state, species) {
if (state[species] && state[species].id)
Vue.set(state, species, null);
}
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
Ensuring reactivity on Array or Object change
// inside single-file component script function
this.$set(someObject, 'propertay', 'newvalue');
this.$set(someArray, 2, 'newvalue');
const index === someArray.indexOf('blah');
if (index !== -1)
someArray.splice(index, 1); // splice removes in place and is reactive by default
// inside mixin, etc
import Vue from 'vue';
Vue.set(someObject, 'propertay', 'newvalue');
Vue.set(someArray, 2, 'newvalue');