## 项目环境
+ @vue-cli:4.5.4
+ node: 14.8.0
## 安装
当前版本的`vue-cli`已经支持vue3.0的preview版本,所以我们可以直接通过以下代码进行安装,在选择版本时选中`vue3.0(preview)`即可。
```shell
vue create [project-name]
```
## setup
> To start working with the Compsition API we first need a place where we can actually use it. In a Vue component, we call this place the `setup`.
```js
export default {
// (e.g. setup (props, { attrs, slots, emit }))
setup (props, context) {
console.log(props);
console.log(context); // 在setup()中,无法访问到this.
}
}
```
## composition API
### reactive()
`reactive()`用于创建一个响应式的引用值.
```vue
{{ title }}
{{ message }}
```
### ref()
`ref()`用于声明一个响应式的原始值,它返回一个对象,该对象只有一个`value属性`。(e.g. `const one = ref(1); // => { value: 1 }`)
我们可以通过`isRef()`来判断某个值是否为一个`ref`。
```vue
{{ title }}
{{ message }}
```
### computed()
vue3.0提供的`computed()`,它可以接受一个回调函数作为参数,也可以接受一个包含了getter、setter的对象作为参数;
```vue
Computed
FirstName: {{ firstName }}
LastName: {{ lastName }}
FullName: {{ fullName }}
ChangeName
```
### watch()
通过`watch()`,我们可以很轻易地监听某个值的变化。
`watch.vue`
```vue
```
`components/Main/WatchOnCleanup.vue`
```vue
```
### LifeCycle
在vue3.0中,提供了与以往版本稍有不同的生命周期钩子
- `beforeCreate()` -> `setup()`
- `created()` -> `setup()`
- `beforeMount()` -> `onBeforeMount()`
- `mounted()` -> `onMounted()`
- `beforeUpdate()` -> `onBeforeUpdate()`
- `updated()` -> `onUpdated()`
- `beforeDestroy()` -> `onBeforeUnmount()`
- `destroyed()` -> `onUnmouted()`
- `errorCaptured()` -> `onErrorCaptured()`
当然,vue3.0是兼容2.x版本的,所以之前的那些生命周期钩子也是可以使用的。
```vue
{{ title }}
{{ item[0] }}
->
{{ item[1] }}
```
output:
```
setup called.
beforeCreate
created
onBeforeMount
beforeMount
onMounted
mounted
onBeforeUpdate
beforeUpdate
onUpdated
updated
onBeforeUnmount
onUnmount
```
### Provide() And Inject()
强大的`provide()`与`inject()`,意味着我们可以用来替代某些需要使用`vuex`来完成工作的场景。
父组件`provide()`提供的值,在其任意的子孙组件中都可以通过`inject()`来获取。
父组件:
```vue
```
`components/Main/ProvideAndInject/Header/index.vue`
```vue
{{ title }}
```
`components/Main/ProvideAndInject/Header/Logo.vue`
```vue
CompHeader Sub Component<{{ logo }}>
```
`components/Main/ProvideAndInject/Content/index.vue`
```vue
From Views/ProvideAndInject:{{ content }}
```
### renderFunction
vue3.0提供`h()`函数来替代以往的`render()`函数。
```vue
```
## 附
[【demo地址】](https://github.com/humandetail/vue3.0-demo)