Vue3+ts learning entry notes

Vue3+ts learning entry notes

(1) Define variables. Define methods

1. setup() function, 2.ref() function

  • Use the setup function.
    We don't need to write data in data and methods in methods. We only need to expose the data and methods, and they can be called anywhere.
  • Use the ref function.
    Realize the two-way binding of data, so that you don't need to define all the data in data like vue2, avoiding unnecessary two-way binding and wasting performance.
<template>
  <div >
    <h1>小葵花妈妈</h1>
    <h2>{
   
   {name}}</h2>
    <br>
    <button @click="changeName">开课了</button>
  </div>
</template>
<script lang="ts">
import { defineComponent,ref } from "vue";//defineComponent函数,引入ref()函数
export default defineComponent({//当写ts语法时,会按照规则匹配提示
  name: "App",
  setup() {
    const name=ref("sss");//利用ref函数实现双向绑定,name指向一个ref对象
    let count=0     //模板中不需要使用,故不暴露出去
    const changeName=function(){//定义函数表达式
      count++
      name.value="哇塞"+count//获取name的值,必须要用name.value来获取
    }
    return {//必须要return暴露出去
      name,
      changeName,
    };
  },
});

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

2. reactive() function

  • Use reactive functions.
    The reactive function can also implement two-way binding data, but it has to pass in an object
<template>
  <div >
    <h1>小葵花妈妈</h1>
    <h2>{
   
   {name.attr}}</h2>//显示必须name.传入的属性名
    <br>
    <button @click="changeName">开课了</button>
  </div>
</template>
<script lang="ts">
import { defineComponent,reactive} from "vue";//引入reactive()函数
export default defineComponent({
  name: "App",
  setup() {
    const name=reactive({attr:"sss"});//必须传入一个对象,属性名自定义
    let count=0
    const changeName=function(){
      count++
      name.attr="哇塞"+count   //用 name.传入的属性名和获取值
    }
    return {
      name,
      changeName,

    };
  },
});

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

Guess you like

Origin blog.csdn.net/weixin_44221744/article/details/112573093