邂逅vue3
# Vue3
# 起步
首先我们需要向Vue.creatApp(obj)这个方法中传入一个对象,Vue通过这个对象中的属性来进行数据渲染,比如template、data、methods
# template属性
template属性可以在obj中这样定义:
template:`
<div>
<h2>{{counter}}</h2>
<button @click='increment'>+</button>
<button @click='decrement'>-</button>
</div>
`,
1
2
3
4
5
6
7
2
3
4
5
6
7
但是很明显这种写法对于开发者并不友好,我们可以通过两种写法定义template
- 写法一:通过 script标签
<script type="x-template" id="hyp">
<div>
<h2>{{counter}}</h2>
<button @click='increment'>+</button>
<button @click='decrement'>-</button>
</div>
</script>
template:`#hyp`, //obj中
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 写法二:使用template标签
<template>
<div>
<h2>{{counter}}</h2>
<button @click='increment'>+</button>
<button @click='decrement'>-</button>
</div>
</template>
template:`#hyp`, //obj中
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8
- 在 createapp的对象中,我们需要传入的 Template以#开头,
- 如果字符串是以#开始,那么它将被用作 queryselector,并且使用匹配元素的 innerhtml作为模板字符串
# data属性
data属性需要传入一个函数,且要返回一个对象
- 在Vue2x的时候,也可以传入个对象(虽然官方推荐是一个函数);
- 在Vue3.x的时候,必须传入一个函数,否则就会直接在浏览器中报错 在data中返回的对象会被响应式系统劫持,因此在之后对改对象进行修改和访问都会在劫持中处理
# methods属性
- methods属性是一个对象,通常我们会在这个对象中定义很多的方法:
- 这些方法可以被绑定到 template 模板中;
- 在该方法中,我们可以使用this关键字来直接访问到data中返回的对象的属性;
- methods中定义的方法不能使用箭头函数定义
- 箭头函数的this绑定的是父级函数的上下文 当定义函数时使用箭头函数 ,那么this会指向window
- 箭头函数中不绑定this
- 源码中对methods中的this处理
this最终绑定的是组件实例对应的代理对象
编辑 (opens new window)
上次更新: 2021/11/29, 19:58:04