- Generate new rails app using
--webpack
flag
rails new myApp --webpack=vue
Note:
- You can use
--webpack=angular
for angular application and--webpack=react
for react.- you can also pass
-J
flag likerails new myApp -J --webpack=vue
to ignore turbolink, but strongly recommend you don't do this, I will see how to make vue js compitable with turbolinks.
-
Keep all of the vue js related codes in
app/javascript/pack/
directory. Anything that needs to be compiled by webpack should go inside this directory. -
app/assets/javascript
is still there for your js and coffescript code that are independed of webpack modules. -
vue-turbolinks
npm module to fix turbolink problems
import TurbolinksAdapter from 'vue-turbolinks';
document.addEventListener('turbolinks:load', () => {
// This code will setup headers of X-CSRF-Token that it grabs from rails generated token in meta tag.
axios.defaults.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').getAttribute('content')
new Vue({
...
mixin: [TurbolinksAdapter],
...
})
})
yarn add vue-turbolink
axios
npm module for making server request (alternative to vue-resource or $.ajax)
yarn add axios
Usage
axios.post('/users', {
firstName: 'John',
lastName: 'Doe',
})
.then(res => console.log(res))
.catch(err => console.log(err));
Example application below:
Thanks so much.
It was really helpful