I'm new to Vue.js and I'm confused about file structure and how to build a simple application.
I have installed Vue CLI on my mac using this command:
npm install -g @vue/cli
Then I created a counter project and used the default option:
vue create counter
Then I started the application:
cd counter
npm run serve
The default application code seemed confusing to me so I want to create my own simple application that makes more sense to me:
I created counter.html inside the public folder:
<html lang="en">
<body>
<div id="counter"></div>
</body>
<script src="../src/counter.js" type="text/javascript"></script>
</html>
I created counter.js file inside the src folder:
import Vue from 'vue';
import Counter from './components/counter.vue';
new Vue({
render: h => h(Counter),
}).$mount('#counter')
I created counter.vue file inside the components folder:
<template>
<button v-on:click="count++">You clicked me {{ count }} times.</button>
</template>
<script type="text/javascript">
export default {
name: 'Counter',
props: [
'count'
],
}
</script>
Then I run:
npm run build
When I visit my page: http://localhost:8080/counter.html I get a blank page and the console shows the following error: Uncaught SyntaxError: Unexpected token <
Any help on what I'm doing wrong is greatly appreciated.
First, As @Dan said, the script tag should be in
<body>
, not after.That said, there's something fundamentally flawed in your code : your button is mutating a property received in the Count component.
Imagine that you're using the Counter in a bigger application, and you want to initialize it with a count value. You'd write :
<Counter count="3" />
, but then clicking would mutate this "3" into a "4", even ifcount="3"
is written statically ; there would be inconsistency between the public declaration of the count property and its actual value due to mutation of the property by the button.Here, you have multiple choices :
and then in your application:
and then in your app:
Basically, the rule of thumb is :
Hoping this help,