Vue3

import { createApp, ref } from 'vue'

createApp({
  setup() {
    return {
      count: ref(0)
    }
  }
}).mount('#app')
<div id="app">
  <button @click="count++">
    Count is: {{ count }}
  </button>
</div>

代码解释

import { createApp, ref } from 'vue'这段代码中 {} 采用了解构赋值,

实际上就是

var createApp = vue.createApp

var ref = vue.ref

  • createApp 是Vue3的新的API,主要用法:配置应用的初始状态、挂载点等,并最终调用 mount 方法来启动应用。

  • ref 响应式引用,当你想要创建一个响应式的数据或属性时,可以使用 ref。这在你需要直接访问或修改响应式数据的值时非常有用。

    const count= ref(0)
    console.log(count.value) // 输出:0  
    count.value++  
    console.log(count.value) // 输出:1
    
  • setup()函数:位于组件逻辑开始的时候,在 beforeCreatecreated 生命周期钩子之前执行

  • 调用了 mount 方法来手动挂载这个 Vue 应用到 DOM 中的某个元素上。上文中应用被挂载到 ID 为 app 的元素上

  • 响应式: Vue 会自动跟踪 JavaScript 状态并在其发生变化时响应式地更新 DOM

Attribute 绑定

<script setup>
import { ref } from 'vue'

const titleClass = ref('title')
</script>

<template>
  <h1 :class="titleClass">Make me red</h1> <!-- 此处添加一个动态 class 绑定 -->
</template>

<style>
.title {
  color: red;
}
</style>
  • ref('title'):可以引用 style里面的样式

事件监听

<script setup>
import { ref } from 'vue'

const count = ref(0)

function increment(){
  count.value++;
}
</script>

<template>
  <!-- 使此按钮生效 -->
  <button @click="increment">count is: {{ count }}</button>
</template>

表单绑定

<script setup>
import { ref } from 'vue'

const text = ref('')

</script>

<template>
  <input v-model="text">
  <p>{{ text }}</p>
</template>

条件渲染

<script setup>
import { ref } from 'vue'

const awesome = ref(true)

function toggle() {
  awesome.value = !awesome.value
}
</script>

<template>
  <button @click="toggle">toggle</button>
  <h1 v-if="awesome">Vue is awesome!</h1>
  <h1 v-else>Oh no 😢</h1>
</template>

列表渲染