一,vue3书写格式
//vue3 主要是按需加载
//书写格式
1.先引入 import { defineComponent,ref } from 'vue';
2.导出 export default defineComponent({
setup(){
//不在使用data 使用setup
}
})
3.定义变量输出结果需要 return {}
4.需要加类型时ref<类型>(1)
5.需要改变一个值的话.value
<!-- 怎么把变量b的值修改成你好世界?? -->
<button @click="modify()">点击时修改</button>
<template>
<div class="box">
{{a}}--{{b}}
</div>
</template>
<script lang="ts">
import { defineComponent,ref } from 'vue';
export default defineComponent({
setup(){
const a= ref<number>(111)
const b= ref<string>('hello wold')
const modify=()=>{
b.value='你好世界'
}
return {a,b,setup}
}
})
</script>
<style scoped lang="less">
.box{
width: 400px;
height: 400px;
border: 1px solid black;
margin: 20px auto;
}
</style>
二.如果你觉得单独定义变量不叫繁琐的话 可以使用reactive实现定义多个变量
<template>
<div class="box">
<!-- 1. obj.name 输出到页面 -->
<!-- {{obj.name}} -->
<!-- 2.不想用obj.怎么办 在return{...toRefs(obj)}用拓展运算符 -->
{{name}} --{{age}}
<button @click="gai()">修改</button>
</div>
</template>
<script lang="ts">
import { defineComponent,reactive,toRefs} from 'vue';
export default defineComponent({
setup(){
const obj = reactive({
name:'张三',
age:18,
})
const gai=()=>{
obj.name='李四'
console.log( obj.name='李四');
}
// return {obj,gai} 1.
return {...toRefs(obj),gai}
}
})
</script>
<style scoped lang="less">
.box{
width: 400px;
height: 400px;
border: 1px solid black;
margin: 20px auto;
}
</style>