官术网_书友最值得收藏!

The app state

As explained before, the state.js file will help us consolidate the main data of our application in one place. That way, it will be easier to write game logic functions without polluting the definition object with a lot of methods.

  1. The state.js file declares a state variable that we will use as the data of our app. We can use it directly as the data option, as follows:
      new Vue({
// …
data: state,
})

Now, if you open the devtools, you should see the only data property already declared in the state object:

The world ratio is a number representing how much we should scale the game objects to fit in the window. For example, .6 means that the world should scale at 60% of its original size. It is computed with the getWorldRatio function in the utils.js file.

There is one thing missing, though--it is not recomputed when the window is resized. This is something we have to implement ourselves. After the Vue instance constructor, add an event listener to the window object to detect when it is resized.

  1. Inside the handler, update the worldRatio data property of the state. You can also display worldRatio in the template:
      new Vue({
name: 'game',
el: '#app',

data: state,

template: `<p id="#app">
{{ worldRatio }}
</p>`,
})

// Window resize handling
window.addEventListener('resize', () => {
state.worldRatio = getWorldRatio()
})

Try resizing your browser window horizontally--the worldRatio data property is updated in the Vue app.

But wait! We are modifying the state object, not the Vue instance...

You are right! However, we have set the Vue instance data property with the state object. This means Vue has set up reactivity on it, and we can change its attributes to update our app, as we will see in a second.

  1. To ensure that state is the app's reactive data, try comparing the instance data object and the global state object:
      new Vue({
// ...
mounted () {
console.log(this.$data === state)
},
})

These are the same objects we set with the data option. So when you do:

this.worldRatio = 42

You are also doing this:

this.$data.worldRatio = 42

This is, in fact, the same as follows:

state.worldRatio = 42

This will be useful in the gameplay function that will use the state object to update the game data.

主站蜘蛛池模板: 万山特区| 昔阳县| 永登县| 霍州市| 乌鲁木齐市| 清远市| 兴和县| 巴塘县| 双鸭山市| 临清市| 镇巴县| 桦甸市| 北碚区| 勐海县| 旬邑县| 哈巴河县| 遵化市| 阿拉善右旗| 绥阳县| 丹巴县| 寿宁县| 鸡泽县| 称多县| 老河口市| 弋阳县| 铜陵市| 将乐县| 七台河市| 平顺县| 慈利县| 吉首市| 长治县| 富顺县| 寿阳县| 安宁市| 河津市| 四会市| 外汇| 拉孜县| 包头市| 淮阳县|