Vue3入门基础之setup语法糖以及响应式的写法区分

第一种 :不采用语法糖以及不考虑响应式数据 


<template>
 <h2>姓名:{
    
    {name}}</h2>
   <h2>年龄:{
    
    {age}}</h2>
   <button @click="say">点击</button>
</template>

<script>
export default {
  name: "App",
  //不采用语法糖,且不考虑响应式数据
  setup(){
    // 数据
    let name = "张三"
    let age = 20
 
    // 方法
    function say(){
      alert(`你好${name},年龄${age}`)
    }
    return {
      name,age,say
    }
  }
};
</script>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

 第二种 : 采用语法糖写法以及响应式数据(基本数据类型)

<template>
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <h3>{
    
    {a}}</h3>
  <button @click="add">+</button>
</template>

<script setup>  //setup语法糖
import {ref} from 'vue'
let a = ref(1)
const add = () =>{
	a.value++
	console.log(a);
}
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
</script>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
<template>
  <div>
    <a href="https://vitejs.dev" target="_blank">
      <img src="/vite.svg" class="logo" alt="Vite logo" />
    </a>
    <a href="https://vuejs.org/" target="_blank">
      <img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
    </a>
  </div>
  <h3>{
   
   {b.name}}</h3>
  <h3>{
   
   {b.age}}</h3>
  <button @click="add">+</button>
</template>

<script setup>  //setup语法糖
import {ref} from 'vue'
let b = ref({    //对象类型
	age : 10,
	name : '张三'
})
const add = () =>{
	b.value.age++
}
// This starter template is using Vue 3 <script setup> SFCs
// Check out https://vuejs.org/api/sfc-script-setup.html#script-setup
</script>

<style scoped>
.logo {
  height: 6em;
  padding: 1.5em;
  will-change: filter;
}
.logo:hover {
  filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
  filter: drop-shadow(0 0 2em #42b883aa);
}
</style>

 ref 函数

  • 作用: 定义一个响应式的数据
  • 语法: const xxx = ref(initValue)
    • 创建一个包含响应式数据的引用对象(reference对象,简称ref对象)
    • JS中操作数据: xxx.value
    • 模板中读取数据: 不需要.value,直接:<div>{ {xxx}}</div>
  • 备注:
    • 接收的数据可以是:基本类型、也可以是对象类型。
    • 基本类型的数据:响应式依靠的是类上的gettersetter完成的
    • 对象类型的数据:内部 “ 求助 ” 了Vue3.0中的一个新函数—— reactive函数。

reactive函数

  • 作用: 定义一个对象类型的响应式数据(基本类型不要用它,要用ref函数)
  • 语法:const 代理对象= reactive(源对象)接收一个对象(或数组),返回一个代理对象(Proxy的实例对象,简称proxy对象)
  • reactive定义的响应式数据是“深层次的”。
  • 内部基于 ES6 的 Proxy 实现,通过代理对象操作源对象内部数据进行操作。

猜你喜欢

转载自blog.csdn.net/tea_tea_/article/details/128118707
今日推荐