Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to conditionally add code in head of Vue app

I have made a simple Vue app using the Vue CLI and now I want to add Google Tag Manager code in the head of the html conditionally only for the production build. I could do this with a server side language like php so I tried changing the index.html to index.php but when I build the project it outputs an index.html with the app injected and the index.php without the app injected in the dist folder. The php code also doesn't work with the webpack-dev-server in the vue cli.

How can I integrate some server side code (it doesn't have to be php) into the index of the vue app generated by the vue cli to conditionally add the tag manager code for the production build? I'm not sure how the vue cli build process is done. Can I tell it to use a different index.html for the production build?

Extra: I'm interested in knowing more about the vue cli build process. ex. There is no script tag in the template index.html so how does Vue inject itself into the index when building or using the webpack-dev-server?

like image 366
Devin Crossman Avatar asked Sep 19 '18 07:09

Devin Crossman


People also ask

How do you use if condition in Vue?

The v-if directive in Vue-js computes a condition to be true into the DOM. When the condition shows false it completely removes the element from the DOM. The if-condition is used in cases where the form element needs to show an error when the user has no input in the input field.

How do you use V-if and V else?

To conditionally render something in Vue, you should use v-if and v-else directives. Simply pass an expression to the v-if directive, and the block will render if the expression is true. You can also use v-else , which will render if the preceeding v-if expression evaluates to a falsy value.

Can you use V for and V-if together?

It's not recommended to use v-if and v-for on the same element due to implicit precedence. Refer to style guide for details.

What is the difference between V-if and V show?

The key difference is that v-if conditionally renders elements and v-show conditionally displayselements. This means that v-if will actually destroy and recreate elements when the conditional is toggled. Meanwhile, v-show will always keep the element in the DOM and will only toggle its display by changing its CSS.


2 Answers

I just saw in the vue cli documentation that the index.html page is processed by webpack. This means I can use lodash template syntax to easily add tags in the head only on production

<head>
...
<%= process.env.NODE_ENV === 'production' ? '<script>...</script>' : '' %>
...
</head>
like image 195
Devin Crossman Avatar answered Sep 27 '22 19:09

Devin Crossman


alternative method:

<% if(process.env.NODE_ENV === 'production') { %>
    <script>...</script>
<% } %>
like image 28
UnDroid System Avatar answered Sep 27 '22 18:09

UnDroid System