首先,使用script指定文件名称
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="showTel">查看联系方式</button>
<button @click="changeName">修改名字</button>
</div>
</template>
<script lang="ts">
export default {
name:'Person',
data(){
return {
name:"张三",
age:18,
tel:"138888888",
count: 1
}
},
methods:{
showTel(){
alert(this.tel)
},
changeName(){
this.name = 'zhangsan' + this.count++
}
}
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px
}
</style>
其次,使用setup函数
setup函数使用后,就不用手动将数据、函数ruturn出去
<template>
<div class="person">
<h2>姓名:{{ name }}</h2>
<h2>年龄:{{ age }}</h2>
<button @click="showTel">查看联系方式</button>
<button @click="changeName">修改名字</button>
<button @click="changeAge">修改年龄</button>
</div>
</template>
<script lang="ts">
export default {
name: "PersonPlus"
};
</script>
<script lang="ts" setup>
import { ref } from 'vue';
// 定义响应式变量
const name = ref<string>("雄安话") // 明确类型为字符串
const age = ref<number>(18) //明确类型为number
const tel= ref<string>("123456789") //明确类型为字符串
const count= ref<number>(1) //明确类型为number
function showTel() {
alert(tel.value);
}
function changeName() {
name.value = `zhangsan${count.value++}`;
}
function changeAge() {
age.value = Number(age.value) + 1;
}
</script>
<style scoped>
.person {
background-color: skyblue;
box-shadow: 0 0 10px;
border-radius: 10px;
padding: 20px;
}
</style>
此时,我们使用了两个script标签,我们尝试将便签合并
<!-- <script lang="ts">
export default {
name: "PersonPlus"
};
</script> -->
<script lang="ts" setup name="PersonPlus123">
import { ref } from 'vue';
// 定义响应式变量
const name = ref<string>("雄安话") // 明确类型为字符串
const age = ref<number>(18) //明确类型为number
const tel= ref<string>("123456789") //明确类型为字符串
const count= ref<number>(1) //明确类型为number
function showTel() {
alert(tel.value);
}
function changeName() {
name.value = `zhangsan${count.value++}`;
}
function changeAge() {
age.value = Number(age.value) + 1;
}
</script>
此时观察界面是不生效的!!!
安装插件,执行语句
npm install vite-plugin-vue-setup-extend
其次,我们配置使用该插件,找到该目录
添加这两行代码:
import VueSetupExtend from 'vite-plugin-vue-setup-extend'
VueSetupExtend()
最后重新启动项目,测试一下
测试成功!!!
使用响应式编程,一定要导入 ref、reactive
import {ref,reactive} from "vue"