User:Saul/vue
This is the page for my notes related to Vue.js
Contents
Vue
Component Properties
data
The data property contains data that your component needs to access. The data property should be a function that returns an object - this so each component has individual data rather that changing all components at once.
export default {
data () {
return {
pageId: this.$router.params.id,
someVarible: "test",
someOtherVarible: 123
};
}
};
props
The props property contains data that is handed down from the parent component or router.
export default {
props: {
someVarible: {
required: true,
type: String
}
}
};
methods
The methods property contains functions that modify the state of the component and will have side effects.
export default {
methods: {
someMethod () {
// do something that has some side effects
return "Result";
}
}
};
computed
The computed property contains functions that compute a result but has no other side effects.
export default {
data(){
return {
search: '',
items: words
}
},
computed: {
filteredItems () {
return this.items.filter(item => {
return item.toLowerCase().search(this.search) > -1;
}).sort();
}
}
};
watch
The watch property contains watches - functions that execute when a varible changes.
export default {
data(){
return {
someVarToWatch: "test"
}
},
watch: {
someVarToWatch: (val) => {
Store.dispatch("setSomeVarToWatch", someVarToWatch);
// run some method to update the page to reflect the change
}
}
};
created
The created property is a function that gets executed when the component is created - it is used to prepare the component.
export default {
data(){
return {
image: new Image()
}
},
created(){
this.image.src = "image.jpg";
this.image.onload = () => {
document.getElementById("image").src = this.image.src;
};
}
};
components
The components property is a object containing the components your component uses like the example below:
<template>
<importedComponent></importedComponent>
</template>
<script>
import importedComponent from "./importedComponent";
export default {
components: {
importedComponent
}
};
</script>
filters
The filters property are used to modify a variable type into a specific format for example timestamps to dates, currencies ect.
Filters are just methods with special syntax in the template section.
<template>
<div>
{{ timestamp | humanFriendlyDate }}
</div>
</template>
<script>
import moment from "moment";
export default {
data () {
return {
timestamp: 1509638478
}
},
filters: {
humanFriendlyDate (date) {
return moment.unix(date).format("MMMM Do YYYY, h:mm:ss a");
}
}
}
</script>
CSS
Scoped
The style section can have the optional parameter "scoped" which makes the css only local to the component it is attached to instead of being global. You may add 2 style tags to your component if you wish to have both local and global css.
<style>
/* global css code */
</style>
<style scoped>
/* local css code */
</style>
Modules
The style section can have the optional parameter "module" which seperates the css from the rest. You have to access the class selectors with the v-bind class parameter likes so:
<template>
<div>
<h1 :class="$style.test">Test 1</h1>
<h1 :class="$style['test-two']">Test 2</h1>
</div>
</template>
<style module>
.test {
color: red;
}
.test-two {
color: blue;
}
</style>
Special Functions
set
Vue cannot detect changes in objects so to manually tell vue to update the data you can use the vue.set() function as shown below:
var object = {
propertyName: "initialValue"
};
var value = "someValue";
Vue.set(object, "propertyName", value);
To use Vue.set you need to import Vue in the file - if you don't want to do this you can use this.$set instead like so:
this.$set(object, "propertyName", value);
emit
To make your component emit a custom event you can use this.$emit like so:
export default {
methods: {
emitEvent () {
this.$emit("emittedEvent", {someData: "data"});
}
}
}
Then you can listen to the event from other components using v-on like demonstrated below:
<template>
<div>
<importedComponent @emittedEvent="doSomething"></importedComponent>
</div>
</template>
<script>
import importedComponent from "@/components/importedComponent";
export default {
components: {
importedComponent
},
methods: {
doSomething () {
console.log("done something");
}
}
}
</script>
Global Properties
You can register properties globally by using Vue.property
It is usually preferable to do this in the main.js file so that it gets registered once.
Here is an example registering a component globally:
The component property is used to register components globally allowing you to use them without importing them in every component that needs it.
import importedComponent from "@/components/importedComponent";
Vue.component("componentName", importedComponent);
html properties
.prevent
.prevent is used as short-hand to prevent default behavior, the following example shows it preventing from submission:
<form @submit.prevent="someMethod">
v-model
v-model is shorthand for :value and @input the two examples below do the same thing:
<input type="text" v-model="someTextVar" />
<input type="text" :value="someTextVar" @input="someTextVar = $event.target.value" />
Vue Router
Router Links
Router links can be used much like the usual a elements:
<a href="/somePage">link</a>
<router-link :to="/somePage">link</router-link>
Or you can specify the router route name and params like so:
<router-link :to="{name: 'Page', params: { id: 123 }}">
link
</router-link>
Where router routes contains something like:
{
path: "/page/:id",
name: "Page",
component: componentName,
props: true
}
History Mode
To set the router to html5 history mode you need to specify the mode parameter in your router.js file like so:
export default new Router({
routes: [
{
path: "/",
name: "Home",
component: Home
}
],
mode: "history"
});
Vuex
Special Functions
Store
The store function is used to create a vuex store like the below example.
new Vuex.Store({
state: {
},
getters: {
},
actions: {
},
mutations: {
}
});
Store Properties
State
The state property is used to hold all the varibles need, and is similar to vue's data property.
new Vuex.Store({
state: {
storedDataOne: "someData",
storedDataTwo: 123,
storedDataThree: [],
storedDataObject: {
objectPropertyOne: []
}
}
});
Getters
The getters property is used to return the data in the format needed, much like vue's computed property.
getters: {
storedDataThreeCount () {
return state.storedDataThree.length;
}
}
Actions
The actions property is used to do more complex actions like fetch data with an ajax call and then call a mutation to update the data, actions can be likened to vue's methods property.
mutations: {
fetchStoredDataTwo (context) {
// Fetch data from server
// context.commit(data);
}
}
To call an action you can use the dispatch method:
store.dispatch("fetchStoredDataTwo");
Mutations
The mutations property is used to do simple changes to the store state.
mutations: {
setStoredDataTwo (state, someNewData) {
state.storedDataTwo = someNewData;
}
}
To run a mutation in a component you first must import the store then commit the state:
store.commit("setStoredDataTwo", 321);
Map Helpers
The map functions are helper functions for access the vuex store - they can significantly reduce your code if you have a lot of computed properties, methods or anything else that only makes a call to the store.
Examples
Here is an example where this code can be reduced significantly:
computed: {
products () {
return this.$store.state.products;
},
cart () {
return this.$store.state.cart;
},
productIsInStock () {
return this.$store.getters.productIsInStock;
}
message () {
return this.$store.getters.message;
}
},
methods: {
checkout: {
$store.dispatch('checkout')
}
}
import {mapState, mapGetters} from "vuex";
// ...
computed: mapState({
products: state => state.products,
cart: "cart" // OR: state => state.cart
}),
methods: mapActions(["checkout"]);
/* OR:
methods: mapActions({
checkout: "checkout"
})
*/
You may change the names of theses properties as well:
import {mapState, mapGetters} from "vuex";
// ...
computed: mapState({
allProducts: state => state.products,
shoppingCart: state => state.cart
})
To copy these functions to the computed property rather than set the computed property to them you can use the spread operator (...)
Final Example
import {mapState, mapGetters} from "vuex";
// ...
computed: {
...mapState({
allProducts: "products" // OR: state => state.products,
shoppingCart: "cart" // OR: state => state.cart
}),
...mapGetters(["productIsInStock", "message"])
},
methods: {
...mapActions(["checkout"])
}
If you compare this to the code not using it you can see that you save a lot of room and simplify code.
List of map helpers
There is a map helper for each vuex store property:
- mapstate
- mapGetters
- mapActions
- mapMutators
Modules
To split a vuex store file up you could import actions from one file getters from another and so on or you can use vuex's module system which is a way to split state up into separate items. You might have a module for authentication another one for your product list, another for your cart and so on.
Module Files
You usually have you store structure setup like this for modules:
store/
modules/
auth.js
cart.js
products.js
index.js
Each module file contains mostly the same code as a store file:
export default {
state: {
},
getters: {
},
actions: {
},
mutations: {
}
}
Each module should only contain the code related to itself.
Imported Modules
To import vuex modules you can use the modules property like so:
import Vuex from "vuex";
import Vue from "vue";
import cart from "./modules/cart";
import products from "./modules/products";
Vue.use(Vuex);
export default new Vuex.Store({
modules: {
auth,
cart,
products
},
state: {
},
getters: {
},
actions: {
},
mutations: {
}
});
The store file should contain the state, actions, etc that uses multiple modules or fit better in a global scope.
Module's Scope
The actions, mutators, and getters in each module are defined in a global scope therefore no change is needed in the components code.
The state property in each module is local so you must define the module who's state you wish to access for example:
computed: {
...mapState({
products: state => state.products.items // INSTEAD OF: state.items
}),
}
The Root State
If you need to access the store file's state from a module or another module you can use the rootState parameter. The getters have the rootState as its third parameter.
getters: {
stateExample (state, getters, rootState) {
// Access the store file's state
console.log(rootState) // This will output the state object in the stores index.js file
console.log(rootState.someVar) // This will output whatever someVar is set to in the stores index.js file
// Accessing other modules state
console.log(rootState.someModule) // This will output the state object in the module "someModule"
console.log(rootState.someModule.someVar) // This will output whatever someVar is set to in the "someModule" module
}
}
Namespaces
One of the problems with modules is that the getters, actions, and mutators are global - therefore when two or more modules have the same action and a component calls that action all of the modules with that action will have that action executed - possibly helpful in some rare cases, or more likely create bugs.
Namespaces are a way to further separate modules - so that the modules have their own local getters, actions, and mutators.
Namespacing Modules
To define a namespace you can set the namespaced property to true like so:
export default {
namespaced: true,
state: {
// ...
}
// ...
}
The Root Getters
The root getters are accessed the same way as the root state. In the getters the "rootGetters" parameter is passed as the fourth parameter.
Here is an example of usage:
getters: {
cartProducts (state, getters, rootState, rootGetters) {
rootGetters["products/productIsInStock"];
}
},
actions: {
addProductToCart ({commit, state, getters, rootState, rootGetters}, product) {
rootGetters["products/productIsInStock"](product);
}
}
Commiting Actions To Other Modules
To commit an action to another module that is a child module of the module or store that is trying to commit the action like this:
commit("products/decrementProductInventory", product);
To commit an action to another module that is not the child module of the module that is trying to commit it you can define the call from root like this:
commit("products/decrementProductInventory", product, {root: true});
Access Namespaced Modules From Components
The components need to specify the namespace's module who's action is getting called. This can be done in two ways as these examples demonstrate for a namespaced "cart" module:
computed: {
...mapGetters({
products: "cart/cartProducts",
total: "cart/cartTotal",
productIsInStock: "products/productIsInStock"
}),
...mapState({
checkoutStatus: state => state.cart.checkoutStatus
})
}
computed: {
...mapGetters("cart", {
products: "cartProducts",
total: "cartTotal"
}),
...mapGetters("products", {
productIsInStock: "productIsInStock"
}),
...mapState("cart", {
checkoutStatus: state => state.checkoutStatus
})
}
Global Store
If you would like store to be accessable global you can define it in the root vue component (usually the main.js file).
import Vue from "vue";
import App from "./App";
import store from "@/store/index";
new Vue({
el: "#app",
store,
render: h => h(App)
});
Then you can access the store from all components without importing it like so:
this.$store
Vue Config
Aliases
By default vue has an alias "@" to reference the src folder in the project
import Home from "@/pages/home";
You can add your own custom aliases by editing the build/webpack.base.config.js file like so:
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
'pages': resolve('src/pages')
}
},
and you can use it like so:
import Home from "pages/home";