vue3.0 ts 初始模板
<template>
<!--Vue2中的html模板中必须要有一对根标签,Vue3组件的html模板中可以没有根标签-->
<img alt="Vue logo" src="./assets/logo.png">
<hello-world msg="Welcome to Your Vue.js + TypeScript App"/>
</template>
<script lang="ts">
// 这里可以使用ts的代码
// defineComponent 函数,目的是定义一个组件,内部可以传入一个配置对象
import { defineComponent } from 'vue';
// 引入一个子级组件
import HelloWorld from './components/HelloWorld.vue';
// 暴露出去一个定义好的组件
export default defineComponent({
// 当前组件的名字是app
name: 'App',
// 注册组件
components: {
// 注册一个子级组件
HelloWorld
}
});
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
2.setup 和 ref 的基本使用
<template>
<div>setup 和 ref 的基本使用</div>
<h3>{{count}}</h3>
<button @click="updateCount">更新数据</button>
</template>
<script lang="ts">
// 这里可以使用ts的代码
// defineComponent 函数,目的是定义一个组件,内部可以传入一个配置对象
import { defineComponent, ref } from 'vue';
// 暴露出去一个定义好的组件
export default defineComponent({
// 当前组件的名字是app
name: 'App',
// vue2.0
// data() {
// return {
// count:0
// }
// },
// methods:{
// updateCount(){
// this.count++
// }
// }
// vue3.0 的方式实现
// setup 是组合式api 的入口函数
setup(){
// 变量
// let count = 0 // 此时的数据并不是响应式的数据(响应式数据变化,页面跟着渲染变化)
// ref 是一个函数,作用:定义一个响应式的数据, 返回的是一个Ref对象,对象中有一个value属性,如果需要对数据进行操作,需要使用该Ref对象调用value属性的方式进行数据操作
// Html模板中是不需要 .value属性写法
// ref 一般用来定义一个基本属性数据
let count = ref(0)
// 方法
function updateCount(){
console.log("===",count)
// 报错原因:count 是一个Ref 对象,对象是不能进行++操作
// count++
count.value++
}
// 返回的是一个对象
return {
//属性
count,
// 方法,
updateCount
}
}
});
</script>