uniapp vue3 <script setup> 用法总结

1.computed:

<template>
  <view>
      <view>{
   
   {getTitle}}</view>
      <view>{
   
   {getMsg(0)}}</view>
  </view>
</template>

<script setup>
	import {computed} from 'vue';

    //不带参数
    const getTitle=computed(() => {
		return 'test'
    })

  //带参数
   const getMsg=computed(()=>{
	   return val=>{
		   return val===0 ? 'success':'fail'
	   }
   })
</script>

2.watch

  1.监听ref

<script setup>

  import {ref,watch} from 'vue';

  const name=ref('');
  const age=ref(10);
  
  //普通监听
  watch(name,(newVal,oldVal=>{
      console.log(newVal,oldVal)
  })

  //初始化监听、深度监听
  	watch(name, (newVal, oldVal) => {
		console.log(newVal, oldVal)
	}, {
		immediate: true,
		deep: true
	})

 //多个值监听
  watch([name, age], (newVal, oldVal) => {
		console.log(newVal, oldVal)
	})

</script>

  2.监听reactive

<script setup>

  import {reactive,watch} from 'vue';

 	const query=reactive({
		name:'xiaodong',
		age:10
	})
  
  //监听整个reactive
  watch(query,(newVal,oldVal=>{
      console.log(newVal,oldVal)
  })

 //监听单个属性
 watch(()=>query.name,(newVal,oldVal=>{
      console.log(newVal,oldVal)
  })

//监听多个属性
 watch([()=>query.name,()=>query.age],(newVal,oldVal=>{
      console.log(newVal,oldVal)
  })


</script>

3.props,emit

<template>
	<view  @click="onClick">{
   
   {title}}</view>
</template>


<script setup>
	const props = defineProps({
		title: {
			type: String,
			default: '',
		},

	})
   
     const emits = defineEmits(['sumbit']);
     const onClick=()=>{
         emits('sumbit');
         emits('sumbit2',{value:props.title})//传值
   }

</script>

4.生命周期函数

  1.vue生命周期函数

Vue2              vue3

beforeCreate  => setup()
created       => setup()
beforeMount   => onBeforeMount
mounted       => onMounted
beforeUpdate  => onBeforeUpdate
updated       => onUpdated
beforeDestroy => onBeforeUnmount
destroyed     => onUnmounted
activated     => onActivated
deactivated   => onDeactivated
errorCaptured => onErrorCaptured
<script setup>
  import { onBeforeMount,onMounted,onUpdated} from 'vue';
    
    onBeforeMount(()=>{
          console.log('onBeforeMount')
     }); 

    onMounted(()=>{
          console.log('onMounted')
     });


    onUpdated(()=>{
          console.log('onUpdated')
     });

</script>

2.小程序生命周期

<script setup>
  import { onShow,onReady,onReachBottom,onShareAppMessage} 
  from '@dcloudio/uni-app';//不支持onLoad
   
   onShow(()=>{
     console.log('onShow')
   });
   
   onReady(()=>{
     console.log('onReady')
   });


  //页面触底监听函数
  onReachBottom(()=>{
    console.log('onReachBottom');
  })

  //分享
  onShareAppMessage(()=>{
    console.log('onShareAppMessage');

  })
</script>

5.页面传值、取值

1.传值和vue2一样

uni.navigateTo({
			url:"/pages/xx/index?id=1"
		})

2.取值

  setup无法导入onLoad,采用vue2 vue3结合写法通过getCurrentInstance()获取组件实例获取

<script>
	export default {
		data() {
			return {
				_id: ''
			}
		},
		onLoad(e) {
			this._id = e.id;
		}
	}
</script>
<script setup>
    import {
		ref,
		getCurrentInstance,
		onBeforeMount,
 	 } from 'vue'
    
    const id=ref('');
    onBeforeMount(()=>{
		id.value=getCurrentInstance().data._id;	
	})
</script>

6.directive

  钩子函数对比

Vue2                       vue3

bind                     created
inserted                 beforeMount
update                   mounted
componentUpdated         beforeUpdate
unbind                   updated
                         beforeUnmount
                         unmounted

1.局部注册

<template>
	<view v-input></view>
</template>

<script setup>

  //命名v开头,v-input
  const vInput={
		created(el,binding){//el绑定元素
			console.log(binding)
		},
		mounted(el,binding){
			console.log(binding)
		},
	    updated(el, binding) {
		    console.log(binding)
		},

	}

</script>

2.全局注册

  main.js

import {
	createSSRApp
} from 'vue'
export function createApp() {
	const app = createSSRApp(App);
	app.directive('input', {
            created(el,binding){
			    console.log(binding)
	     	},
			mounted(el, binding) {
				console.log(binding)
			},
			updated(el, binding) {
				console.log(binding)
			},


		})
	return {
		app
	}
}

7.provide\inject

//父组件

<script setup>
 	import { provide } from 'vue';
    provide('value',1);
</script>



//子组件

<script setup>
 	import { inject } from 'vue';
    const value=inject('value');
</script>

 注意:inject()只能放在setup()生命周期里运行,诸如放在setTimeout或promise将获取失败

inject() can only be used inside setup() or functional components.

8.slot,attr 

<script setup>
import { useSlots, useAttrs } from 'vue'

  const slots = useSlots()
  const attrs = useAttrs()
</script>

9.sync,v-model

  统一用v-model:xxx

//父组件
<parent v-model:visible="visible"></parent>



//子组件
<child v-show="visible" @click="onClose"></child>

<script setup>
	const props = defineProps({
		visible: {
			type: Boolean,
			default: false,
		}
	})

   
    const emits = defineEmits(['update:visible'])
    const onClose=()=>{
        emits('update:visible', false);
     }
</script>

10.Vue原型绑定

//vue2

main.js:
Vue.prototype.$url = baseUrl;

页面调用:this.$url



//vue3

main.js:
const app = createSSRApp(App);
app.config.globalProperties.$url = baseUrl;

页面调用:

 <script setup>

   import { getCurrentInstance } from 'vue';

   const { proxy } = getCurrentInstance();
   const url=proxy.$url
 </script>

11.全局注册组件、使用插件

main.js:

import tabs from 'xxxxxx';//组件
import plug from 'xxxxxxx'//插件

//vue2:
import Vue from 'vue';
Vue.component("tabs",tabs)
Vue.use(plug)



//vue3
import { createSSRApp } from 'vue';

export function createApp() {

	const app = createSSRApp(App);
	app.component("tabs", tabs);
	app.use(plug);
	
    return {
		app
	}
}

猜你喜欢

转载自blog.csdn.net/sd1sd2/article/details/122846609