Skip to content

Commit

Permalink
Add in debugging recipe, delete unused categories from cookbook TOC (v…
Browse files Browse the repository at this point in the history
…uejs#1464)

* add in debugging recipe, delete unused categories from cookbook TOC

* VSCode => VS Code

* update PR based on review- title edits, clarification of sourcemaps, point to readmes
  • Loading branch information
sdras authored Mar 21, 2018
1 parent 80d60d3 commit 5c6e98b
Show file tree
Hide file tree
Showing 7 changed files with 152 additions and 29 deletions.
Binary file added src/images/breakpoint_hit.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/breakpoint_set.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/config_add.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/devtools-timetravel.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added src/images/vuetron-heirarchy.gif
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
68 changes: 39 additions & 29 deletions src/v2/cookbook/adding-instance-properties.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,15 +8,15 @@ order: 2

There may be data/utilities you'd like to use in many components, but you don't want to [pollute the global scope](https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch3.md). In these cases, you can make them available to each Vue instance by defining them on the prototype:

``` js
```js
Vue.prototype.$appName = 'My App'
```

Now `$appName` is available on all Vue instances, even before creation. If we run:

``` js
```js
new Vue({
beforeCreate: function () {
beforeCreate: function() {
console.log(this.$appName)
}
})
Expand All @@ -36,23 +36,23 @@ No magic is happening here. `$` is a convention Vue uses for properties that are
Another great question! If you set:

``` js
```js
Vue.prototype.appName = 'My App'
```

Then what would you expect to be logged below?

``` js
```js
new Vue({
data: {
// Uh oh - appName is *also* the name of the
// instance property we defined!
appName: 'The name of some other app'
},
beforeCreate: function () {
beforeCreate: function() {
console.log(this.appName)
},
created: function () {
created: function() {
console.log(this.appName)
}
})
Expand All @@ -66,7 +66,7 @@ Let's say you're replacing the [now-retired Vue Resource](https://medium.com/the

All you have to do is include axios in your project:

``` html
```html
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.15.2/axios.js"></script>

<div id="app">
Expand All @@ -78,22 +78,23 @@ All you have to do is include axios in your project:

Alias `axios` to `Vue.prototype.$http`:

``` js
```js
Vue.prototype.$http = axios
```

Then you'll be able to use methods like `this.$http.get` in any Vue instance:

``` js
```js
new Vue({
el: '#app',
data: {
users: []
},
created () {
created() {
var vm = this
this.$http.get('https://jsonplaceholder.typicode.com/users')
.then(function (response) {
this.$http
.get('https://jsonplaceholder.typicode.com/users')
.then(function(response) {
vm.users = response.data
})
}
Expand All @@ -106,34 +107,40 @@ In case you're not aware, methods added to a prototype in JavaScript gain the co

Let's take advantage of this in a `$reverseText` method:

``` js
Vue.prototype.$reverseText = function (propertyName) {
this[propertyName] = this[propertyName].split('').reverse().join('')
```js
Vue.prototype.$reverseText = function(propertyName) {
this[propertyName] = this[propertyName]
.split('')
.reverse()
.join('')
}

new Vue({
data: {
message: 'Hello'
},
created: function () {
console.log(this.message) // => "Hello"
created: function() {
console.log(this.message) // => "Hello"
this.$reverseText('message')
console.log(this.message) // => "olleH"
console.log(this.message) // => "olleH"
}
})
```

Note that the context binding will __not__ work if you use an ES6/2015 arrow function, as they implicitly bind to their parent scope. That means the arrow function version:
Note that the context binding will **not** work if you use an ES6/2015 arrow function, as they implicitly bind to their parent scope. That means the arrow function version:

``` js
```js
Vue.prototype.$reverseText = propertyName => {
this[propertyName] = this[propertyName].split('').reverse().join('')
this[propertyName] = this[propertyName]
.split('')
.reverse()
.join('')
}
```

Would throw an error:

``` log
```log
Uncaught TypeError: Cannot read property 'split' of undefined
```

Expand All @@ -143,27 +150,30 @@ As long as you're vigilant in scoping prototype properties, using this pattern i

However, it can sometimes cause confusion with other developers. They might see `this.$http`, for example, and think, "Oh, I didn't know about this Vue feature!" Then they move to a different project and are confused when `this.$http` is undefined. Or, maybe they want to Google how to do something, but can't find results because they don't realize they're actually using Axios under an alias.

__The convenience comes at the cost of explicitness.__ When looking at a component, it's impossible to tell where `$http` came from. Vue itself? A plugin? A coworker?
**The convenience comes at the cost of explicitness.** When looking at a component, it's impossible to tell where `$http` came from. Vue itself? A plugin? A coworker?

So what are the alternatives?

## Alternative Patterns

### When Not Using a Module System

In applications with __no__ module system (e.g. via Webpack or Browserify), there's a pattern that's often used with _any_ JavaScript-enhanced frontend: a global `App` object.
In applications with **no** module system (e.g. via Webpack or Browserify), there's a pattern that's often used with _any_ JavaScript-enhanced frontend: a global `App` object.

If what you want to add has nothing to do with Vue specifically, this may be a good alternative to reach for. Here's an example:

``` js
```js
var App = Object.freeze({
name: 'My App',
description: '2.1.4',
helpers: {
// This is a purely functional version of
// the $reverseText method we saw earlier
reverseText: function (text) {
return text.split('').reverse().join('')
reverseText: function(text) {
return text
.split('')
.reverse()
.join('')
}
}
})
Expand All @@ -175,7 +185,7 @@ Now the source of these shared properties is more obvious: there's an `App` obje

Another advantage is that `App` can now be used _anywhere_ in your code, whether it's Vue-related or not. That includes attaching values directly to instance options, rather than having to enter a function to access properties on `this`:

``` js
```js
new Vue({
data: {
appVersion: App.version
Expand Down
113 changes: 113 additions & 0 deletions src/v2/cookbook/debugging-in-vscode.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
---
title: Debugging in VS Code and Chrome
type: cookbook
order: 8
---

Every application reaches a point where it's necessary to understand failures, small to large. In this recipe, we explore a few workflows for VS Code users, who are using Chrome to test.

This recipe shows how to use the [Debugger for Chrome](https://github.com/Microsoft/VSCode-chrome-debug) extension with VS Code to debug Vue.js applications generated by the [Vue CLI](https://github.com/vuejs/vue-cli).

## Prerequisites

You must have Chrome and VS Code installed. Make sure to get the latest version of [Debugger for Chrome](https://marketplace.visualstudio.com/items?itemName=msjsdiag.debugger-for-chrome) extension installed in VS Code.

Install and create a project with the [vue-cli](https://github.com/vuejs/vue-cli), with the instructions for installation documented in the readme of the project. Change into the newly created application directory and open VS Code.

### Showing Source Code in the Chrome Devtools

Before you can debug your Vue components from VS Code you need to update the generated Webpack config to build sourcemaps. We do this so that our debugger has a way to map the code within a compressed file back to its position in the original file. This ensures that you can debug an application even after your assets have been optimized by Webpack.

Go to `config/index.js` and find the `devtool` property. Update it to:

```json
devtool: 'source-map',
```

### Launching the Application from VS Code

Click on the Debugging icon in the Activity Bar to bring up the Debug view, then click on the gear icon to configure a launch.json file, selecting **Chrome** for the environment. Replace content of the generated launch.json with the following two configurations:

![Add Chrome Configuration](/images/config_add.png)

```json
{
"version": "0.2.0",
"configurations": [
{
"type": "chrome",
"request": "launch",
"name": "vuejs: chrome",
"url": "http://localhost:8080",
"webRoot": "${workspaceFolder}/src",
"breakOnLoad": true,
"sourceMapPathOverrides": {
"webpack:///src/*": "${webRoot}/*"
}
}
]
}
```

## Setting a Breakpoint

1. Set a breakpoint in **src/components/HelloWorld.vue** on `line 90` where the `data` function returns a string.

![Breakpoint Renderer](/images/breakpoint_set.png)

2. Open your favorite terminal at the root folder and serve the app using Vue CLI:

```
npm start
```

3. Go to the Debug view, select the **'vuejs: chrome'** configuration, then press F5 or click the green play button.

4. Your breakpoint should now be hit as the new instance of Chrome opens `http://localhost:8080`.

![Breakpoint Hit](/images/breakpoint_hit.png)

## Alternative Patterns

### Vue Devtools

There are other methods of debugging, varying in complexity. The most popular and simple of which is to use the excellent [vue-devtools](https://chrome.google.com/webstore/detail/vuejs-devtools/nhdogjmejiglipccpnnnanhbledajbpd). Some of the benefits of working with the devtools are that they enable you to live-edit data properties and see the changes reflected immediately. The other major benefit is the ability to do time travel debugging for Vuex.

![Devtools Timetravel Debugger](/images/devtools-timetravel.gif)

<p class="tip">Please note that if the page uses a production/minified build of Vue.js (such as the standard link from a CDN), devtools inspection is disabled by default so the Vue pane won't show up. If you switch to an unminified version, you may have to give the page a hard refresh to see them.</p>

### Vuetron

[Vuetron](http://vuetron.io/) is a really nice project that extends some of the work that vue-devtools has done. In addition to the normal devtools workflow, you are able to:

* Quickly view API Request/Response: if you're using the fetch API for requests, this event is displayed for any request sent. The expanded card displays the request data as well as the response data.
* Subscribe to specific parts of your application’s state for faster debugging
* Visualize component hierarchy, and an animation allows you to collapse or expand the tree for specific hierarchy views.

![Vuetron Heirarchy](/images/vuetron-heirarchy.gif)

### Simple Debugger Statement

The example above has a great workflow. However, there is an alternative option where you can use the [native debugger statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger) directly in your code. If you choose to work this way, it's important that you remember to remove the statements when you're done.

```js
<script>
export default {
data() {
return {
message: ''
}
},
mounted() {
const hello = 'Hello World!'
debugger
this.message = hello
}
};
</script>
```

## Acknowledgements

This recipe was based on a contribution from [Kenneth Auchenberg](https://twitter.com/auchenberg), [available here](https://github.com/Microsoft/VSCode-recipes/tree/master/vuejs-cli).

0 comments on commit 5c6e98b

Please sign in to comment.