vue3中的写法以及,一些语法糖

vue3新增setup,属性执行比 created更早,同时setup中this不会指向实例)这个方法在onBeforeMounted之前被调用。


定义数据需要在数据前面加ref,ref在vue3中是将数据转换成响应式数据结构的一种,

因为vue3中没有了data(){ },那么就没办法劫持数据做到响应式数据,所以使用ref。

以下解释ref:

1.什么是ref

ref和reactive一样,也是用来实现响应式数据的方法

由于reactive必须传递一个对象,所以在实际开发中如果只是想让某个变量实现响应式的时候回非常麻烦

所以Vue3提供了ref方法实现简单值得监听

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

// ref写法
const num = ref(100);
const str = ref('qwert');
const bol = ref(true);

const obj = ref({
cup : 'D',
height : 180
});

// reactive写法
const people = reactive({
age : 18,
name : 'tom'
})

// ref与reactive 修改/赋值
num.value = 200
people.age = 23

</script>

2.ref本质

ref底层其实还是reactive,所以当运行时系统会自动根据传入的ref转换成reactive.

3.ref注意点

在vue中使用ref的值不用通过value获取

在js中使用ref的值必须通过value获取

<template>
  <div>xxx</div>
</template>
<script setup>
  //setup自带语法糖
  //setup中没有this,所有的方法必须引入后使用 
  import {ref} from 'vue'
 let aa  =ref(123)
</script>
----------------------------------------
//系统自动return 相当于以下写法
----------------------------------------
<template>
  <div>xxx</div>
</template>
<script>
import {ref} from 'vue'
export default{
  setup() {
    //定义数据需要在数据前面加ref
    let aa=ref(123)
    return{
     aa
    }
  }
}
</script>

定义函数的写法,方法的绑定

<template>
  <div>
    <button @click="btn"></button>
  </div>
</template>
<script setup>
// 定义函数的写法
let btn = ()=>{
  console.log("匿名函数");
}
function btn(){
  console.log('普通函数');
}
</script>

定义组件使用defineProps语法糖,在 <script setup> 中可直接使用 defineProps 和 defineEmits API 来声明 props 和 emits ,它们具备完整的类型推断并且在 <script setup> 中是直接可用的,无需引入。

    //子组件中-- 定义Props
    const props = defineProps<{
        msg: number,
        name: string
    }>()
//-------------------------

  //父组件
<Aone name="结果" :msg="1"></Aone>

下面是一个综合小demo:

//组件名 Aone.vue
<template>
  这是a组件 -- {
    
    { msg }}
</template>

<script setup lang="ts">

const props = defineProps({
  msg: String
})

</script>

<style>

</style>
<template>
  <div>
    [{
    
    { count }}]
    <button @click="inf">+1</button>
    <br>
    ----------
    <br>
  </div>

  <div>
    <!-- 引入a组件 -->
    <Aone :msg="msg"></Aone>
  </div>

  <div>
    <!-- 绑定输入框到msg -->
    <input type="text" v-model="msg">
  </div>

</template>

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

const count = ref(0)
// msg初值为123
const msg = ref('123')
const inf = () => {
  count.value++
}

</script>

<style>

</style>

猜你喜欢

转载自blog.csdn.net/ONLYSRY/article/details/128615290