Simple use of vue3 Composition API

Vue3 can choose to use the optons configuration API used in vue2, or you can choose to use the new Composition API. Write a simple demo below to experience the use of the combined API.

setup

The setup function is a new component option. As the entry point for using Composition API within the component. The this point in setup is different from the this point in vue2, do not use this in the setup function

reactive

The reactive function accepts an ordinary object and returns a reactive data object

ref

The ref function receives a basic type of data and returns a response data. The value of the data created by the ref function in the setup function needs to use xxxx.value, but it can be used directly outside the setup function.

Life cycle

  • beforeCreate -> 使用 setup()
  • created -> 使用 setup()
  • beforeMount -> onBeforeMount
  • mounted -> onMounted
  • beforeUpdate -> onBeforeUpdate
  • updated -> onUpdated
  • beforeDestroy -> onBeforeUnmount
  • destroyed -> onUnmounted
  • errorCaptured -> onErrorCaptured

watch

Monitor data changes, you can manually end

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>vue3 Composition API</title>
</head>
<body>
	<div id="app">
		{
   
   {count}}
		<p>姓名:{
   
   {content.name}}</p>
		<p>年龄:{
   
   {content.age}}</p>
		<input type="text" v-model="content.name">
		<button @click="change">修改</button>
	</div>

	<!-- <script src="lib/vue3.js"></script> -->
	<script src="https://unpkg.com/vue@next"></script>
	<script>
		const {
     
     reactive,ref,createApp,onMounted,watch} = Vue;
		createApp({
     
     
			// 第一个参数props,第二个参数提供了一个上下文对象,从原来 2.x 中 this 选择性地暴露了一些 property。
			setup(props,context ){
     
     
				// reactive函数接受一个普通对象,返回一个响应式数据对象
				const content = reactive({
     
     
					name:'张三'
				})
				// ref函数接收一个基本类型数据,返回一个响应式数据
				let count = ref(0)

				const stop = watch(()=>content.name,(val)=>{
     
     
					console.log('监听content.name的变化',val)
				})

				setTimeout(()=>{
     
     
					stop()
				},2000)

				// setup 也可以返回一个函数,函数中也能使用当前 setup 函数作用域中的响应式数据:
				function change(){
     
     
					content.name = '李四'
					content.age = content.age?content.age+1:1
				}

				onMounted(()=>{
     
     
					console.log('onMounted',count.value)
				})

				return{
     
     
					content,
					count,
					change
				}
			}

		}).mount('#app')
	</script>
</body>
</html>

Guess you like

Origin blog.csdn.net/weixin_35958891/article/details/107934072