How to Set up Vue.js with Phoenix 1.4
Start by creating a new Phoenix project. We use the --no-ecto
flag here, since we don’t need a database for the example.
$ mix phx.new vue_example --no-ecto
Then cd into the new projects assets directory and install the dependencies we need:
$ cd vue_example/assets
$ npm install vue vue-loader vue-template-compiler --save-dev
Phoenix comes preconfigured with Webpack, so all we need to do is modify the file assets/webpack.config.js
First, include the VueLoaderPlugin in the list of imports:
const { VueLoaderPlugin } = require('vue-loader');
Next, in the list of rules, add a rule for vue files:
{
test: /\.vue$/,
exclude: /node_modules/,
loader: 'vue-loader',
}
Lastly, add the VueLoader plugin in the list of plugins:
plugins: [
...
new VueLoaderPlugin()
],
The finished file should look something like this:
Now create a folder assets/js/components
. We’ll put our Vue components here. Create a file Message.vue
in this folder:
We now need to import this component in assets/js/app.js
. Add the following lines to the end of this file:
Now all that’s left is display this in a HTML template. Replace the contents of lib/vue_example_web/templates/page/index.html.eex
with this:
<div id="hello"></div>
That’s it. Start the server (mix phx.server
) and go to http://localhost:4000, and you should see a button provided by Vue.