tips: vue2.0 和 vue3.0的区别
- 没有data methods computed 那些内容了 而是用setup()函数代替
-
<template>
里的“根元素”不再只能是一个了
一. setup() 函数
现在, 我们没有必要把数据写在 data里 把方法写在methods 里了
我们把数据和方法写在setup里, 再通过return 暴露出去
<template>
<h2>请选择服务员:</h2>
<div>
<button
v-for="(name, index) in girls"
v-bind:key="index"
@click="selectGirlFun(index)"
>
{
{ index }}:{
{ name }}
</button>
</div>
<h2>您选择了:{
{ selectedGirl }}!!</h2>
</template>
<script lang="ts">
import { defineComponent, ref } from "vue";
export default defineComponent({
name: "App",
setup() {
const girls = ref(["貂蝉", "王昭君", "西施", "杨玉环"]);
const selectedGirl = ref("");
const selectGirlFun = (index: number) => {
selectedGirl.value = girls.value[index];
};
return {
girls,
selectedGirl,
selectGirlFun,
};
},
});
</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>
二. ref() 函数
我们看到, 上述例程中使用了 ref()函数
ref()
这个函数使得我们的变量拥有了双向绑定属性,
这是和vue2.0中写在data里就可以双向绑定是不同的.
下面我们通过一个错误的例程和 修改后正确的例程来说明此函数
错误的例程