前言

提示:Vue3.2 版本开始才能使用语法糖!

在 Vue3.0 中变量必须 return 出来,template中才能使用;而在 Vue3.2 中只需要在 script 标签上加上 setup 属性,无需 return,template 便可直接使用,非常的香啊!

提示:以下是本篇文章正文内容,下面案例可供参考

一、如何使用setup语法糖

只需在 script 标签上写上setup

代码如下(示例):

<template>
</template>
<script setup>
</script>
<style scoped lang="less">
</style>

二、data数据的使用

由于 setup 不需写 return,所以直接声明数据即可

代码如下(示例):

<script setup>
    import {
      ref,
      reactive,
      toRefs,
    } from 'vue'
    
    const data = reactive({
      patternVisible: false,
      debugVisible: false,
      aboutExeVisible: false,
    })
    
    const content = ref('content')
    //使用toRefs解构
    const { patternVisible, debugVisible, aboutExeVisible } = toRefs(data)
</script>

三、method方法的使用

代码如下(示例):

<template >
    <button @click="onClickHelp">系统帮助</button>
</template>
<script setup>
import {reactive} from 'vue'

const data = reactive({
      aboutExeVisible: false,
})
// 点击帮助
const onClickHelp = () => {
    console.log(`系统帮助`)
    data.aboutExeVisible = true
}
</script>

四、watchEffect的使用

watchEffect与watch的区别

相比Vue2,Vue3多了watchEffect这个API,watchEffect传入一个函数参数,该函数会立即执行,同时会响应式的最终函数内的依赖变量,并在依赖发生改变时重新运行改函数。

const name = ref<string>('张三')
const age = ref<number>(18)

watchEffect(() => {
  console.log(`${name.value}:${age.value}`) // 张三:18
})

setTimeout(() => {
  name.value = '李四' // 李四:18
}, 3000)

setTimeout(() => {
  age.value = 20 // 李四:20
}, 5000)

和watch的区别:

运行时机不同,watchEffect会立即执行,相当于设置了immediate: true的watch。
watchEffect无法获取改变前后的值。
与watch显示的指定依赖源不同,watchEffect会自动收集依赖源。

用watchEffect还是watch?

建议在大部分时间里使用watch,避免一些不必要的重复触发。

五、watch的使用

基础数据类型的监听:

const name = ref<string>('张三')
watch(name, (newValue, oldValue) => {
  console.log('watch===', newValue, oldValue)
})

复杂数据类型的监听::

interface UserInfo {
  name: string
  age: number
}

const userInfo = reactive<UserInfo>({
  name: '张三',
  age: 10
})
// 监听整个对象
watch(userInfo, (newValue, oldValue) => {
  console.log('watch userInfo', newValue, oldValue)
})

// 监听某个属性
watch(() => userInfo.name,  (newValue, oldValue) => {
  console.log('watch name', newValue, oldValue)
})

支持监听多个源

在Vue3里,watch多了一个特性,可以传入一个数组同时侦听多个数据,这比起Vue2确实优雅多了,以往在Vue2中为了实现同时监听多个数据,往往需要借助computed,现在在Vue3里我们可以少一些不必要的代码了。

const name = ref<string>('张三')
const userInfo = reactive({
  age: 18
})

// 同时监听name和userInfo的age属性
watch([name, () => userInfo.age], ([newName, newAge], [oldName, oldAge]) => {
  // 
})

六、computed计算属性的使用

computed计算属性有两种写法(简写和考虑读写的完整写法)

代码如下(示例):

<script setup>
    import {
      reactive,
      computed,
    } from 'vue'

    //数据
    let person = reactive({
       firstName:'小',
       lastName:'叮当'
     })
    // 计算属性简写
    person.fullName = computed(()=>{
        return person.firstName + '-' + person.lastName
      }) 
    // 完整写法
    person.fullName = computed({
      get(){
        return person.firstName + '-' + person.lastName
      },
      set(value){
        const nameArr = value.split('-')
        person.firstName = nameArr[0]
        person.lastName = nameArr[1]
      }
    })
</script>

七、props父子传值的使用

子组件代码如下(示例):

<template>
  <span>{{props.name}}</span>
</template>

<script setup>
  import { defineProps } from 'vue'
  // 声明props
  const props = defineProps({
    name: {
      type: String,
      default: '11'
    }
  })  
  // 或者
  //const props = defineProps(['name'])
</script>
父组件代码如下(示例):
<template>
  <child :name='name'/>  
</template>

<script setup>
    import {ref} from 'vue'
    // 引入子组件
    import child from './child.vue'
    let name= ref('小叮当')
</script>

八、emit子父传值的使用

子组件代码如下(示例):

<template>
   <a-button @click="isOk">
     确定
   </a-button>
</template>
<script setup>
import { defineEmits } from 'vue';

// emit
const emit = defineEmits(['aboutExeVisible'])
/**
 * 方法
 */
// 点击确定按钮
const isOk = () => {
  emit('aboutExeVisible');
}
</script>
父组件代码如下(示例):
<template>
  <AdoutExe @aboutExeVisible="aboutExeHandleCancel" />
</template>
<script setup>
import {reactive} from 'vue'
// 导入子组件
import AdoutExe from '../components/AdoutExeCom'

const data = reactive({
  aboutExeVisible: false, 
})
// content组件ref


// 关于系统隐藏
const aboutExeHandleCancel = () => {
  data.aboutExeVisible = false
}

</script>

九、获取子组件ref变量和defineExpose暴露

即vue2中的获取子组件的ref,直接在父组件中控制子组件方法和变量的方法

子组件代码如下(示例):

<template>
    <p>{{data }}</p>
</template>

<script setup>
import {
  reactive,
  toRefs
} from 'vue'

/**
 * 数据部分
 * */
const data = reactive({
  modelVisible: false,
  historyVisible: false, 
  reportVisible: false, 
})
defineExpose({
  ...toRefs(data),
})
</script>
父组件代码如下(示例):
<template>
    <button @click="onClickSetUp">点击</button>
    <Content ref="content" />
</template>

<script setup>
import {ref} from 'vue'

// content组件ref
const content = ref('content')
// 点击设置
const onClickSetUp = ({ key }) => {
   content.value.modelVisible = true
}

</script>
<style scoped lang="less">
</style>

十、路由useRoute和useRouter的使用

代码如下(示例):

<script setup>
  import { useRoute, useRouter } from 'vue-router'
    
  // 声明
  const route = useRoute()
  const router = useRouter()
    
  // 获取query
  console.log(route.query)
  // 获取params
  console.log(route.params)

  // 路由跳转
  router.push({
      path: `/index`
  })
</script>

十一、store仓库的使用

代码如下(示例):

<script setup>
  import { useStore } from 'vuex'
  import { num } from '../store/index'

  const store = useStore(num)
    
  // 获取Vuex的state
  console.log(store.state.number)
  // 获取Vuex的getters
  console.log(store.state.getNumber)
  
  // 提交mutations
  store.commit('fnName')
  
  // 分发actions的方法
  store.dispatch('fnName')
</script>

十二、await的支持

setup 语法糖中可直接使用 await,不需要写 async , setup 会自动变成 async setup

代码如下(示例):

<script setup>
  import Api from '../api/Api'
  const data = await Api.getData()
  console.log(data)
</script>

十三、provide 和 inject 祖孙传值

父组件代码如下(示例):

<template>
  <AdoutExe />
</template>

<script setup>
  import { ref,provide } from 'vue'
  import AdoutExe from '@/components/AdoutExeCom'

  let name = ref('Jerry')
  // 使用provide
  provide('provideState', {
    name,
    changeName: () => {
      name.value = '小叮当'
    }
  })
</script>
子组件代码如下(示例):
<script setup>
  import { inject } from 'vue'
  const provideState = inject('provideState')

  provideState.changeName()
</script>

十四、v-model

支持多个v-model

在Vue3中,可以通过参数来达到一个组件支持多个v-model的能力。

// 父组件
<template>
  <child v-model="name" v-model:email="email" />
  <p>姓名:{{ name }}</p>
  <p>邮箱:{{ email }}</p>
</template>

<script lang="ts" setup>
import child from './child.vue'
import { ref } from 'vue'

const name = ref<string>('张三')
const email = ref<string>('666@qq.com')
</script>
// 子组件
<template>
  <button @click="updateName">更新name</button>
  <button @click="updateEmail">更新email</button>
</template>

<script lang="ts" setup>
// 定义emit
const emits = defineEmits<{
  (e: 'update:modelValue', value: string): void
  (e: 'update:email', value: string): void
}>()

const updateName = () => {
  emits('update:modelValue', '李四')
}

const updateEmail = () => {
  emits('update:email', '123456@qq.com')
}
</script>

如果v-model没有使用参数,则其默认值为modelValue,如上面的第一个v-model,注意此时不再是像Vue2那样使用$emit(‘input’)了,而是统一使用update:xxx的方式。

废弃.sync

在Vue2中,由于一个组件只支持一个v-model,当我们还有另外的值也想要实现双向绑定更新时,往往用.sync修饰符来实现,而在Vue3中该修饰符已被废弃,因为v-model可以支持多个,所以.sync也就没有存在的必要了。

十五、$attrs

Vue3中,$attrs包含父组件中除props和自定义事件外的所有属性集合。

不同于Vue2,$attrs包含了父组件的事件,因此$listenners则被移除了。

// 父组件
<template>
  <child id="root" class="test" name="张三" @confirm="getData" />
</template>

<script lang="ts" setup>
const getData = () => {
  console.log('log')
}
</script>

// 子组件
<template>
  <div>
    <span>hello:{{ props.name }}</span>
  </div>
</template>

<script lang="ts">
export default {
  inheritAttrs: false
}
</script>

<script lang="ts" setup>
const props = defineProps(['name'])

const attrs = useAttrs()
console.log('attrs', attrs)
</script>

在这里插入图片描述
使用v-bind即可实现组件属性及事件透传:

// 父组件
<template>
  <child closeable @close="onClose" />
</template>

<script lang="ts" setup>
const onClose = () => {
  console.log('close')
}
</script>

// 子组件
<template>
  <div>
    <el-tag v-bind="attrs">标签</el-tag>
  </div>
</template>

十六、使用ref访问子组件

在Vue2中,使用ref即可访问子组件里的任意数据及方法,但在Vue3中则必须使用defineExpose暴露子组件内的方法或属性才能被父组件所调用。

// 父组件
<template>
  <child ref="childRef" />
</template>

<script lang="ts" setup>
import { ref, onMounted } from 'vue'

const childRef = ref()

onMounted(() => {
  childRef.value.getData()
})
</script>

// 子组件
<script lang="ts" setup>
import { defineExpose } from 'vue'

const getData = () => {
  console.log('getData')
}
const name = ref('张三')

defineExpose({
  getData,
  name
})
</script>
Logo

前往低代码交流专区

更多推荐