vue3+ts学习入门笔记
(1)定义变量.定义方法
1. setup() 函数 ,2.ref()函数
- 利用setup函数。
我们就没有必要把数据写在 data里 把方法写在methods 里了,只需将数据,和方法暴露出去,就可以在任何地方调用。 - 利用ref函数。
实现数据的双向绑定,这样就可以不用像vue2一样,将数据都定义在data里,避免一些不必要的双向绑定,浪费性能。
<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() 函数
- 利用reactive函数。
reactive函数可以同样实现双向绑定数据,但是它得传入个对象
<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>