Vue入门教程的几个小坑

1.vue中data必须是一个函数。

虽然在教程的例子中大多直接写成这样:

1
2
3
data: {
message:'message'
}

但是如果在组件中这样写会导致数据影响到所有复用组件,所以应该改为这样:

1
2
3
4
5
data(){
return {
message:'message'
}
}

官网的例子可以很好的说明这个问题:https://cn.vuejs.org/v2/guide/components.html

1
2
3
4
5
6
7
8
9
10
11
12
Vue.component('button-counter', {
data: function () {
return {
count: 0
}
},
//改成这样试试
//data: {
// count: 0
//},
template: '<button>You clicked me {/{count/}} times.</button>'
})
1
2
3
4
5
<div id="components-demo">
<button-counter></button-counter>
<button-counter></button-counter>
<button-counter></button-counter>
</div>

2.组件中的template必须被html标签包裹。

上面的例子,如果去掉标签就不显示了,比如像这样:

1
template: 'You clicked me {/{count/}} times.'

3.注意箭头函数()=>{} 与function()的区别。

箭头函数的this永远指向定义函数的环境,而function中指向的是调用该函数的对象。比如官网上的这个例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
new Vue({
el: '#app',
data () {
return {
info: null
}
},
mounted () {
axios
.get('https://api.coindesk.com/v1/bpi/currentprice.json')
.then(response => (this.info = response))
//如果改写成这样就会失败
//.then(function(response){this.info = response})
//非要用function那就只能这么写
//.then(function(response){that.info = response});
//var that = this
}
})