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>
component
The component property is used to register components globally allowing you to use them without importing them in every component that needs it.
It is usually preferable to do this in the main.js file so that it gets registered once.
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);
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";