Java攻城狮的Vue3学习笔记:Day003

99 阅读1分钟

用老Java工程师的思维记录Vue3的学习过程,希望能帮助后端同学们快速上手前端。虽然说以后都是AI编程了,但是AI写出来的东西咱也得能看懂吧?

Day 003

计算属性 computed

<script setup>
import { reactive, computed } from 'vue'

const author = reactive({
  name: 'John Doe',
  books: [
    'Vue 2 - Advanced Guide',
    'Vue 3 - Basic Guide',
    'Vue 4 - The Mystery'
  ]
})

// a computed ref
const publishedBooksMessage = computed(() => {
  return author.books.length > 0 ? 'Yes' : 'No'
})
</script>

<template>
  <p>{{author.name}} has published books:</p>
  <span>{{ publishedBooksMessage }}</span>
</template>

条件渲染 v-if/v-else

  • v-if/v-else
<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>

列表渲染

  • v-for
<script setup>
import { ref } from 'vue'

const parentMessage = ref('Parent')
const items = ref (
    [  
        { message: 'Foo' },
        { message: 'Bar' },
        { message: 'XXX' }
    ])
</script>

<template>
	<li v-for="(item, index) in items">
  	{{ parentMessage }} - {{ index }} - {{ item.message }}
	</li>
</template>
<script setup>
import { ref } from 'vue'

// 给每个 todo 对象一个唯一的 id
let id = 0

const newTodo = ref('')
const todos = ref([
  { id: id++, text: 'Learn HTML' },
  { id: id++, text: 'Learn JavaScript' },
  { id: id++, text: 'Learn Vue' }
])

function addTodo() {
  todos.value.push({ id: id++, text: newTodo.value })
  newTodo.value = ''
}

function removeTodo(todo) {
  todos.value = todos.value.filter((t) => t !== todo)
}
</script>

<template>
  <form @submit.prevent="addTodo">
    <input v-model="newTodo">
    <button>Add Todo</button>    
  </form>
  <ul>
    <li v-for="todo in todos" :key="todo.id">
      {{ todo.text }}
      <button @click="removeTodo(todo)">X</button>
    </li>
  </ul>
</template>

JS知识点

  • 运算符 !== 不绝对等于(值和类型有一个不相等,或两个都不相等)
  • 结合箭头函数 todos.value.filter((t) => t !== todo) 直观去看,就是把当前的todo从todos数组中过滤掉(保留不等于todo的)