Home >Web Front-end >JS Tutorial >Getting up and Running with the Vue.js 2.0 Framework

Getting up and Running with the Vue.js 2.0 Framework

Jennifer Aniston
Jennifer AnistonOriginal
2025-02-14 10:16:12524browse

Getting up and Running with the Vue.js 2.0 Framework

Want to learn Vue.js from scratch? SitePoint Premium offers a complete collection of Vue books covering the basics, projects, tips and tools, and more. Join now for just $14.99 per month.

This article has been updated, mainly updated the tool section.

Since the release of the popular JavaScript framework Vue.js version of v2, I can't wait to try it out and see how it feels like. As someone who is very familiar with Angular and React, I look forward to seeing the similarities and differences between them and between Vue.

Vue 2 has excellent performance metrics, relatively small loads (the bundled Vue runtime version weighs about 30KB after shrinking and gzip compression), and state management of supporting libraries such as vue-router and Vuex, Vue library) update. It's too much to cover everything in just one article, but please pay attention to the follow-up articles and we'll look at the various libraries that are perfectly integrated with the core framework more carefully.

Key Points

  • Vue.js 2.0 introduces React-inspired virtual DOM for efficient rendering and integrates improved libraries such as vue-router and Vuex for state management.
  • Components are the basis of Vue.js 2.0, where applications are built into a series of nested components and a single file component (.vue) is recommended to better organize your code.
  • Setting up Vue projects from scratch requires webpack and vue-loader to process .vue files, and Babel to use modern JavaScript capabilities to enhance development workflow.
  • Vue Devtools is essential for debugging, which provides insight into the state of the application and how data flows through the components.
  • Vue.js 2.0 facilitates the construction of interactive forms by leveraging v-model for bidirectional data binding and using v-on for custom event processing, thus making state management seamless between components.
  • This article demonstrates building a GitHub user statistics acquisition application that uses Vue's reactive system and lifecycle hooks to effectively manage and display data, and illustrates the actual usage of Vue.js in real scenarios.

Inspiration from other libraries

As you learn this tutorial, you will see that Vue has many features that are obviously inspired by other frameworks. This is a good thing; it's great to see new frameworks draw on some ideas from other libraries and improve them. In particular, you'll see that Vue's templates are very close to Angular's templates, but their component and component lifecycle approaches are closer to React's (and Angular's).

A such example is that, like React and nearly all frameworks in today's JavaScript field, Vue uses the concept of virtual DOM to maintain rendering efficiency. Vue uses a branch of snabbdom, one of the more popular virtual DOM libraries. The Vue website contains documentation about its virtual DOM rendering, but as a user, you just need to know that Vue is very good at keeping rendering speed (actually, in many cases, it performs better than React), which means you can rest assured that you A reliable platform is being built.

Components, Components, Components

Like other frameworks today, Vue's core building blocks are components. Your application should be a series of components that are built to each other to generate the final application. Vue.js goes a step further, suggesting (although not mandatory) that you define components in a .vue file, and then the build tool (which we'll cover in a short time) can parse those files. Given that the purpose of this article is to fully explore Vue and its usage, I will use this convention for this application.

Vue file is as follows:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

Or, if you don't like to put all parts of the component in a single file, you can provide each element with a src attribute and point to a separate HTML, JS, or CSS file, respectively.

Settings Project

While the excellent Vue CLI makes it easy to set up a full project, I like to start from scratch when starting with the new library so I can learn more about these tools.

Now, webpack is my preferred build tool, which we can use in conjunction with the vue-loader plugin to support the Vue.js component format I mentioned earlier. We also need Babel and env presets so that we can write all the code using modern JavaScript syntax, as well as webpack-dev-server, which updates the browser when file changes are detected.

Let's initialize a project and install the dependencies:

<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

Then create the initial folder and file:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>

The project structure should be as follows:

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

Let's set up the webpack configuration now. This boils down to the following points:

  • Tell webpack to use vue-loader
  • for any .vue file
  • Tell webpack to use Babel and env presets for any .js file
  • Tell webpack to use src/index.html as a template to generate an HTML file for dev-server to provide services:
<code class="language-javascript">//webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html"
    })
  ]
}</code>

Finally, we will add some content to the HTML file and we can start!

<code class="language-html"><!DOCTYPE html>

  
    <title>My Vue App</title>
  
  
    <div id="app"></div>
  
</code>

We created an empty div with ID of app because this is the element we will place the Vue app. I always prefer to use divs rather than body elements, as this gives me control over the rest of the page.

Writing our first Vue.js application

We will stay true to every previous programming tutorial, write a Vue application, and put "Hello, World!" on the screen before delving into more complex content.

Each Vue application is created by importing the library and then instantiating a new Vue instance:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

We provide Vue with an element to render to the page, so we create a Vue application! We pass a selector to select the element we want Vue to replace with our application. This means that when Vue runs, it will take the div#app we created and replace it with our application.

The reason we use the variable name vm is because it represents the "view model". Although not strictly associated with the Model View Model Model (MVVM) pattern, Vue is partially inspired by it, and the convention to use the variable name vm to represent Vue applications has been used to this day. Of course, you can name variables as you like!

So far, our app does nothing, so let's create our first component, App.vue, which will actually render something onto the page.

Vue does not specify the structure of the application, so it is up to you. I ended up creating a folder for each component, in this case App (I like capital letters, which means a component), which contains three files:

  • index.vue
  • script.js
  • style.css
<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

The file structure should now look like this:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>

App/index.vue defines the template and imports other files. This fits the structure recommended in the "About Separation of Concerns" section of the Vue documentation.

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

I like to name it index.vue, but you might also want to name it app.vue for easier search. I prefer to import App/index.vue in my code rather than App/app.vue, but again, you may not agree, so feel free to choose any name you and your team like the most.

At present, our template is just

Hello, World!

, I leave the CSS file empty. The main work is done in script.js, which looks like this:

<code class="language-javascript">//webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html"
    })
  ]
}</code>

Doing so creates a component that we will name as App, which is mainly for debugging purposes, which I will cover later, and then defines the data that the component owns and is responsible for. Currently, we don't have any data, so we can tell Vue this by returning an empty object. Later, we will see an example of a component that uses data.

Now we can go back to src/index.js and tell the Vue instance to render our App components:

<code class="language-html"><!DOCTYPE html>

  
    <title>My Vue App</title>
  
  
    <div id="app"></div>
  
</code>

First, we import the component, and believe that webpack and vue-loader will be responsible for parsing it. Then we declare the component. This is an important step: by default, the Vue component is not globally available. Each component must have a list of all the components they will use, and the tags it will be mapped to. In this case, because we register our component like this:

<code class="language-javascript">import Vue from 'vue'

const vm = new Vue({
  el: '#app',
})</code>

This means that in our template we will be able to use the app element to reference our components.

Finally, we define the render function. This function uses a helper (usually called h) call that is able to create elements. It's not very similar to the React.createElement function used by React. In this case, we provide it with the string 'app' because the component we are rendering is registered as having the tag app.

Most cases (and in the rest of this tutorial), we won't use the render function on other components, because we will define the HTML template. However, if you want to learn more, it's worth reading Vue.js' guide on render functions.

After

The last step is to create an npm script in package.json:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

Now, run npm run start. Your default browser should open at https://www.php.cn/link/03b0db8c971432a5e8d163897176a7cc and you should see "Hello, World!" on your screen.

Try editing src/index.vue to change the message to something else. If all goes well, webpack-dev-server should refresh the page to reflect your changes.

Great! We are running using Vue.js.

Vue Devtools

Before we dig into a slightly more complex Vue application, it's time to mention that you should definitely install Vue devtools. These are located in Chrome Developer Tools, giving you a great way to view your application and all the passed properties, the state each component has, and more.

Getting up and Running with the Vue.js 2.0 Framework

Build the application

As a sample application, we will use the GitHub API to build an application, let's enter a username and view some GitHub statistics for that user. I chose the GitHub API here because it is familiar to most people, can be used without authentication, and it provides us with a lot of information.

Before starting the application, I like to quickly think about what components we need, I think our App component will render two other components: GithubInput, which is used to receive input from the user, and GithubOutput, which will display the user's screen information on. We will start with input.

Note: You can find all the code on GitHub and even view applications running online.

Initial Settings

Create folders for GithubOutput and GithubInput components in the src directory:

<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

Add necessary files to each folder:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>
The structure of the

src folder should now look like this:

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

Forms in Vue.js

Let's start with the GithubInput component. Like App components, the index.vue file should contain templates, as well as load scripts and CSS files. Currently, the template only contains

github input

. We will fill it in correctly soon. I like to put in some virtual HTML so that I can check if my template is correctly connected when creating a new component:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

What we do differently when creating this component is creating snippets of data associated with the component. This is very similar to React's concept of state:

<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

This means that this component has a piece of data it owns and is responsible for, i.e. username. We will soon update it based on user input.

Finally, in order to put this component on the screen, I need to register it with the App component because the App component will render it.

For this, I update src/App/script.js and tell it GithubInput:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>

Then I can update the template of the App component:

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

One limitation of Vue components (as is true in Angular and React) is that each component must have a root node, so when the component has to render multiple elements, it is important to remember to wrap them all in something, most A common one is div.

Track form input

Our GithubInput component needs to do two things:

  • Tracking the current value of input
  • conveys that the value has been changed so that other components can know and update their status as a result.

We can complete the first version by creating a form containing input elements. We can use Vue's built-in directives to track form values. The template for GithubInput is as follows:

<code class="language-javascript">//webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html"
    })
  ]
}</code>

You will notice that there are two important properties: v-on and v-model.

v-on is how we bind to DOM events and call functions in Vue. For example,

Click me!

Whenever a paragraph is clicked, the component's foo method is called. If you want to learn more about event handling, I highly recommend Vue's documentation on event handling. v-model creates a two-way data binding between form input and data. Behind the scenes, v-model is actually listening for change events on form input and updating data in Vue components to match.

Considering our template above, here is how we use v-on and v-model to process data in the form:

  • v-on:submit.prevent="onSubmit" Runs onSubmit when binding the method onSubmit to form submission. By adding .prevent, this means that Vue will automatically prevent the default action from happening. (If Vue does not do this, we can call event.preventDefault() in the code, but we might as well take advantage of Vue's functionality.)
  • v-model:username Bind the entered value to the value username in the code. For those familiar with Angular, you may realize that this is very similar to ng-model. When we create GithubInput we declare that it has a piece of data username, where we bind that data to the input field. Both will automatically remain synchronized.

Now, back to our component's JavaScript, we can declare the onSubmit method. Note that the name here is completely arbitrary - you can choose any name at will - but I like to stick to the convention of using functions named according to the event that will trigger the event:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

We can directly reference the data on this, so this.username will provide the latest value of the text box. If it is not empty, we want other components to know that the data has changed. To do this, we will use the message bus. These are objects that components can issue events and use to listen for other events. When your application gets bigger, you may want to consider a more structured approach, such as Vuex. Currently, the message bus can do this.

The good news is that we can use an empty Vue instance as the message bus. To do this, we will create src/bus.js, which just creates a Vue instance and exports it:

<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

In the GithubInput component, we can import the module and use it by issuing events when the username changes:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>

In this way, our form is completed and we can start doing something with the generated data.

Show results from GitHub

The GithubOutput component has the same structure as our other two components. In GithubOutput/script.js we also import the bus module because we need it to know when the username changes. The data this component will be responsible for will be an object that maps the GitHub username to the data we get from the GitHub API. This means we don't have to make a request to the API every time; if we've fetched the data before, we can simply reuse it. We will also store the last username we received so that we know what data is displayed on the screen:

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

When creating a component, we want to listen for any new-username event emitted on the message bus. Thankfully, Vue supports many life cycle hooks, including created. Because we are responsible developers, we will also stop listening to events using the destroyed event when component destruction:

<code class="language-javascript">//webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html"
    })
  ]
}</code>

Then we define the onUsernameChange method, which will be called and set the currentUsername property:

<code class="language-html"><!DOCTYPE html>

  
    <title>My Vue App</title>
  
  
    <div id="app"></div>
  
</code>

Note that we do not have to explicitly bind the onUsernameChange method to the current scope. When you define a method on a Vue component, Vue automatically calls myMethod.bind(this) to it, so they are always bound to the component. This is one of the reasons why you need to define methods for components on methods object so that Vue can fully understand them and set them accordingly.

Conditional Rendering

If we don't have a username - we won't have it when the component is first created - we want to show a message to the user. Vue has many conditional rendering techniques, but the simplest is the v-if directive, which accepts a condition and renders elements only if the condition exists. It also works with v-else:

<code class="language-javascript">import Vue from 'vue'

const vm = new Vue({
  el: '#app',
})</code>

Again, this is very familiar to any Angular developer. We use a double sign instead of a triple sign here, because we want the condition to be true not only when currentUsername is null, but also when currentUsername is undefined , and null == undefined is true.

Get data from GitHub

Vue.js does not come with its own HTTP library, and that's for good reason. Today, the fetch API is natively included in many browsers (although at the time of writing, except for IE11, Safari, or iOS Safari). For the sake of this tutorial, I won't use polyfill, but if you need it, you can easily add polyfill for the API in your browser. If you don't like the fetch API, there are many third-party libraries for HTTP, and one mentioned in the Vue documentation is Axios.

I am very supportive of frameworks like Vue that do not include HTTP libraries. It reduces the bundle size of the framework and allows developers to choose the library that best suits them, and easily customizes requests as needed to communicate with their API. I'll stick with the fetch API in this article, but you can feel free to replace it with any library you like.

If you need to know about the fetch API, check out the post on Ludovico Fischer on SitePoint, which will get you started quickly.

To make HTTP requests, we will provide the component with another method fetchGithubData, which makes a request to the GitHub API and stores the results. It will also first check if we already have the data for this user, and if not, no request will be made:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

Then we just need to trigger this method when the username changes:

<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

One more thing to note is that since Vue tracks the data you are using, it knows when to update the view. There is a great reactive guide explaining it in detail, but essentially Vue can't magically know when you have added or removed properties from objects, so if we do:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>

Vue will not recognize this and will not update our views. Instead, we can use a special Vue.set method, which explicitly tells Vue that we have added a key. The above code will look like this:

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

This code will modify this.githubData, adding the keys and values ​​we pass to it. It also notifies Vue of changes so that it can be rerendered.

Now our code looks like this:

<code class="language-javascript">//webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html"
    })
  ]
}</code>

Lastly, we need to register the GitHubOutput component using the App component:

<code class="language-html"><!DOCTYPE html>

  
    <title>My Vue App</title>
  
  
    <div id="app"></div>
  
</code>

and include it in the template:

<code class="language-javascript">import Vue from 'vue'

const vm = new Vue({
  el: '#app',
})</code>

Although we have not written a view code to display the retrieved data on the screen, you should be able to fill out the form with your username and then check Vue devtools to view the data requested from GitHub. This shows how practical and powerful these devtools are; you can check the local status of any component and see exactly what is going on.

Show some statistics in the view

We can now update the template to display some data. Let's wrap this code in another v-if directive so that we will render the data only after the request is completed:

<code class="language-bash">mkdir src/App
touch src/App/{index.vue,script.js,style.css}</code>

This way, we can now render the GitHub details to the screen and our application is done!

Refactor

We can definitely make some improvements. The HTML code that renders GitHub data above requires only a small part of the data of the current user. This is a perfect case for another component, we can provide user data to it, it can render it.

Let's create a GithubUserData component with the same structure as our other components:

<code class="language-html"><template>
  <p>This is my HTML for my component</p>
</template>



<style scoped>
  /* CSS here
   * by including `scoped`, we ensure that all CSS
   * is scoped to this component!
   */
</style></code>

There is only one small difference in this component: it will get a property data, which will be the user's data. Properties (or "props") are bits of data that a component will pass by its parent component, and they behave very similarly in Vue to React. In Vue you have to explicitly declare every property the component needs, so here I will say that our component will get a property data:

<code class="language-bash">mkdir vue2-demo-project
cd vue2-demo-project
npm init -y
npm i vue
npm i webpack webpack-cli @babel/core @babel/preset-env babel-loader vue-loader vue-template-compiler webpack-dev-server html-webpack-plugin --save-dev</code>

The thing I really like about Vue is that you have to be very clear; all the properties, data, and components that the component will use are explicitly declared. This makes the code easier to use, and I believe that as the project gets bigger and more complex, it is easier to maintain.

In the new template, we have the exact same HTML as before, although we can refer to data instead of githubData[currentUsername]:

<code class="language-bash">mkdir src
touch webpack.config.js src/index.html src/index.js</code>

In order to use this component, we need to update the GithubOutput component. First, we import and register GithubUserData:

<code>.
├── package.json
├── package-lock.json
├── src
│   ├── index.html
│   └── index.js
└── webpack.config.js</code>

You can use any name when declaring the component, so where I put github-user-data you can place whatever name you want. It is recommended that you stick to components containing dashes. Vue does not enforce this, but the W3C specification for custom elements states that they must contain dashes to prevent lifename conflicts with elements added in future versions of HTML.

After declaring the component, we can use it in the template:

<code class="language-javascript">//webpack.config.js
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const HtmlWebPackPlugin = require("html-webpack-plugin")

module.exports = {
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
      },
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    new HtmlWebPackPlugin({
      template: "./src/index.html"
    })
  ]
}</code>

The crucial point here is how I pass the data attribute to the component:

<code class="language-html"><!DOCTYPE html>

  
    <title>My Vue App</title>
  
  
    <div id="app"></div>
  
</code>

The colon at the beginning of this property is crucial; it tells Vue that the properties we pass are dynamic and that the components should be updated every time the data changes. Vue will evaluate the value of githubData[currentUsername] and ensure that the GithubUserData component remains up to date as the data changes.

If you find :data a little short and magical, you can also use a longer v-bind syntax:

<code class="language-javascript">import Vue from 'vue'

const vm = new Vue({
  el: '#app',
})</code>

The two are equivalent, so please use any of your preference.

Conclusion

In this way, our GitHub application is in a pretty good state! You can find all the code on GitHub and even view applications running online.

I had high hopes for Vue when I started using it because I've heard a lot of good things and I'm happy to say it did meet my expectations. Using Vue feels like taking the best parts of React and merging them with the best parts of Angular. Some directives (such as v-if, v-else, v-model, etc.) are very easy to get started (and easier to understand immediately than conditional judgments in React's JSX syntax), but Vue's component system feels very similar to React's .

You should break the system down into small components, and overall, I found it to be a very seamless experience. I can’t give enough praise to the Vue team’s documentation yet: it’s absolutely great. The guide is excellent, the API reference is comprehensive, and easy to navigate to find the exact thing you want.

If you like this post and want to learn more, the best starting point is definitely the official Vue.js website.

Frequently Asked Questions about Vue.js 2.0

What is the main difference between Vue.js 1.0 and Vue.js 2.0?

Vue.js 2.0 has several improvements over its predecessor. The most important change is the introduction of a virtual DOM, which improves performance by reducing direct operations on the actual DOM. Vue.js 2.0 also introduces a simplified component-based development syntax to make building complex user interfaces easier. Additionally, Vue.js 2.0 supports server-side rendering, which improves the performance of your application and makes it easier to optimize SEO.

How to use observers in Vue.js 2.0?

The observer in Vue.js 2.0 allows you to execute custom logic when data properties change. To use observer, you need to define a function with the same name as the data attribute you want to observe and add it to the "watch" object in the Vue instance. This method is called whenever the data attribute changes and its new and old values ​​are taken as parameters.

What is the urgent loading in Vue.js and how can I use it?

Emergency loading is a concept in Vue.js that allows you to load data from the server before you need it, thereby improving the performance of your application. To use urgent loading in Vue.js, you can use the "created" lifecycle hook to get data from the server when the component is created. This data will then be available immediately after the component is rendered.

How to use computed properties in Vue.js 2.0?

Computed properties in Vue.js 2.0 allow you to define reusable properties calculated based on your data. To use computed properties, you need to define a method that returns the computed value and add it to the computed object in the Vue instance. This method is called whenever any data attributes it depends on change, and its return value is cached until the dependency changes again.

How to handle events in Vue.js 2.0?

Vue.js 2.0 provides a powerful event handling system that allows you to listen on DOM events and run custom logic when events occur. To handle events, you need to use the "v-on" directive in the template, followed by the name of the event to be listened to and the method to run when the event occurs. This method will be called using the event object as its parameter.

How to use Vue.js 2.0 with Laravel?

Vue.js 2.0 can be easily integrated with Laravel, a popular PHP framework. Laravel comes with Vue.js support, so you can start building Vue.js components right away. To use Vue.js in a Laravel project, you need to include the Vue.js script in HTML and then define the Vue component in a separate JavaScript file.

How to use Vue.js 2.0 with Webpack?

Webpack is a module bundler that can be used to bundle Vue.js components into a single JavaScript file. To use Vue.js with Webpack, you need to install the "vue-loader" package, which allows Webpack to understand Vue components. You can then import Vue components in your JavaScript file and use them as usual.

How to use Vue.js 2.0 with TypeScript?

Vue.js 2.0 supports TypeScript, a statically typed superset of JavaScript. To use Vue.js with TypeScript, you need to install the "vue-class-component" package, which allows you to define Vue components using the TypeScript class. You can then define the Vue component as a TypeScript class and use TypeScript's static typed functionality to catch errors at compile time.

How to use Vue.js 2.0 with Vuex?

Vuex is a state management library for Vue.js that allows you to manage the state of your application in a centralized storage. To use Vuex with Vue.js, you need to install the "vuex" package and then define your status, mutations, actions, and getters in the Vuex storage. You can then use the "this.$store" property to access your state and schedule actions from the Vue component.

How to use Vue.js 2.0 with Vue Router?

Vue Router is a routing library for Vue.js that allows you to define routes for your application. To use Vue Router with Vue.js, you need to install the "vue-router" package and then define your route in the Vue Router instance. You can then use the "router-link" component to navigate between routes and use the "router-view" component to display the currently routed components.

The above is the detailed content of Getting up and Running with the Vue.js 2.0 Framework. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:A Deep Dive into ReduxNext article:A Deep Dive into Redux